Compare commits

..

8 Commits

Author SHA1 Message Date
5042df4874 Merge pull request 'fix' (#12) from queues into dev
Reviewed-on: #12
2024-11-17 13:09:31 +03:00
7fd853f300 Merge pull request 'fix' (#11) from queues into dev
Reviewed-on: #11
2024-11-17 13:06:04 +03:00
6a0471dc15 Merge pull request 'add' (#10) from queues into dev
Reviewed-on: #10
2024-11-17 13:01:49 +03:00
cc290465a1 Merge pull request 'queues' (#9) from queues into dev
Reviewed-on: #9
2024-11-17 12:58:54 +03:00
1d0abfed03 Merge pull request 'fix' (#6) from master into dev
Reviewed-on: #6
2024-10-11 06:50:59 +03:00
e17c5ab7fe Merge pull request 'master' (#5) from master into dev
Reviewed-on: #5
2024-10-11 06:49:45 +03:00
ff7f0ffa91 Merge pull request 'fix' (#3) from master into dev
Reviewed-on: #3
2024-10-11 06:13:49 +03:00
71a12ef77b Merge pull request 'fix' (#2) from master into dev
All checks were successful
Build and push / Build (push) Successful in 5s
Build and push / Push (push) Successful in 8s
Reviewed-on: #2
2024-10-11 05:46:11 +03:00
21 changed files with 263 additions and 144 deletions

BIN
.DS_Store vendored

Binary file not shown.

View File

@@ -2,17 +2,46 @@ version: "3.4"
services:
poll:
image: mathwave/sprint-repo:pizda-bot
command: poll
environment:
TELEGRAM_TOKEN: $TELEGRAM_TOKEN_DEV
STAGE: "development"
QUEUES_TOKEN: $QUEUES_TOKEN_DEV
deploy:
mode: replicated
restart_policy:
condition: any
update_config:
parallelism: 1
order: start-first
worker:
image: mathwave/sprint-repo:pizda-bot
command: worker
environment:
MONGO_HOST: "mongo"
MONGO_HOST: "mongo.develop.sprinthub.ru"
MONGO_PASSWORD: $MONGO_PASSWORD_DEV
STAGE: "development"
networks:
- queues-development
- configurator
- mongo-development
QUEUES_TOKEN: $QUEUES_TOKEN_DEV
PLATFORM_SECURITY_TOKEN: $PLATFORM_SECURITY_TOKEN
deploy:
mode: replicated
restart_policy:
condition: any
update_config:
parallelism: 1
order: start-first
mailbox:
image: mathwave/sprint-repo:pizda-bot
command: mailbox
environment:
TELEGRAM_TOKEN: $TELEGRAM_TOKEN_DEV
STAGE: "development"
QUEUES_TOKEN: $QUEUES_TOKEN_DEV
deploy:
mode: replicated
restart_policy:
@@ -25,12 +54,13 @@ services:
image: mathwave/sprint-repo:pizda-bot
command: api
environment:
MONGO_HOST: "mongo"
TELEGRAM_TOKEN: $TELEGRAM_TOKEN_DEV
MONGO_HOST: "mongo.develop.sprinthub.ru"
MONGO_PASSWORD: $MONGO_PASSWORD_DEV
PLATFORM_SECURITY_TOKEN: $PLATFORM_SECURITY_TOKEN
STAGE: "development"
networks:
- common-infra-nginx-development
- mongo-development
- common-infra-nginx
deploy:
mode: replicated
restart_policy:
@@ -40,11 +70,5 @@ services:
order: start-first
networks:
common-infra-nginx-development:
external: true
queues-development:
external: true
configurator:
external: true
mongo-development:
common-infra-nginx:
external: true

View File

@@ -2,17 +2,46 @@ version: "3.4"
services:
poll:
image: mathwave/sprint-repo:pizda-bot
command: poll
environment:
TELEGRAM_TOKEN: $TELEGRAM_TOKEN_PROD
STAGE: "production"
QUEUES_TOKEN: $QUEUES_TOKEN_PROD
deploy:
mode: replicated
restart_policy:
condition: any
update_config:
parallelism: 1
order: start-first
worker:
image: mathwave/sprint-repo:pizda-bot
command: worker
environment:
MONGO_HOST: "mongo"
MONGO_HOST: "mongo.sprinthub.ru"
MONGO_PASSWORD: $MONGO_PASSWORD_PROD
STAGE: "production"
networks:
- queues
- configurator
- mongo
QUEUES_TOKEN: $QUEUES_TOKEN_PROD
PLATFORM_SECURITY_TOKEN: $PLATFORM_SECURITY_TOKEN
deploy:
mode: replicated
restart_policy:
condition: any
update_config:
parallelism: 1
order: start-first
mailbox:
image: mathwave/sprint-repo:pizda-bot
command: mailbox
environment:
TELEGRAM_TOKEN: $TELEGRAM_TOKEN_PROD
STAGE: "production"
QUEUES_TOKEN: $QUEUES_TOKEN_PROD
deploy:
mode: replicated
restart_policy:
@@ -25,11 +54,13 @@ services:
image: mathwave/sprint-repo:pizda-bot
command: api
environment:
MONGO_HOST: "mongo"
TELEGRAM_TOKEN: $TELEGRAM_TOKEN_PROD
MONGO_HOST: "mongo.sprinthub.ru"
MONGO_PASSWORD: $MONGO_PASSWORD_PROD
PLATFORM_SECURITY_TOKEN: $PLATFORM_SECURITY_TOKEN
STAGE: "production"
networks:
- common-infra-nginx
- mongo
deploy:
mode: replicated
restart_policy:
@@ -41,9 +72,3 @@ services:
networks:
common-infra-nginx:
external: true
queues:
external: true
configurator:
external: true
mongo:
external: true

View File

@@ -28,7 +28,7 @@ jobs:
run: docker push mathwave/sprint-repo:pizda-bot
deploy-dev:
name: Deploy dev
runs-on: [prod]
runs-on: [dev]
needs: push
steps:
- name: login
@@ -39,5 +39,8 @@ jobs:
ref: dev
- name: deploy
env:
TELEGRAM_TOKEN_DEV: ${{ secrets.TELEGRAM_TOKEN_DEV }}
MONGO_PASSWORD_DEV: ${{ secrets.MONGO_PASSWORD_DEV }}
run: docker stack deploy --with-registry-auth -c ./.deploy/deploy-dev.yaml pizda-bot-development
PLATFORM_SECURITY_TOKEN: ${{ secrets.PLATFORM_SECURITY_TOKEN }}
QUEUES_TOKEN_DEV: ${{ secrets.QUEUES_TOKEN_DEV }}
run: docker stack deploy --with-registry-auth -c ./.deploy/deploy-dev.yaml pizda-bot

View File

@@ -39,5 +39,8 @@ jobs:
ref: prod
- name: deploy
env:
TELEGRAM_TOKEN_PROD: ${{ secrets.TELEGRAM_TOKEN_PROD }}
MONGO_PASSWORD_PROD: ${{ secrets.MONGO_PASSWORD_PROD }}
PLATFORM_SECURITY_TOKEN: ${{ secrets.PLATFORM_SECURITY_TOKEN }}
QUEUES_TOKEN_PROD: ${{ secrets.QUEUES_TOKEN_PROD }}
run: docker stack deploy --with-registry-auth -c ./.deploy/deploy-prod.yaml pizda-bot

2
.gitignore vendored
View File

@@ -117,5 +117,3 @@ GitHub.sublime-settings
!.vscode/launch.json
!.vscode/extensions.json
.history
*pb2*

51
.gitlab-ci.yml Normal file
View File

@@ -0,0 +1,51 @@
stages:
- build
- deploy-dev
- deploy-prod
build:
stage: build
tags:
- dev
before_script:
- docker login -u mathwave -p $DOCKERHUB_PASSWORD
script:
- docker build -t mathwave/sprint-repo:pizda-bot .
push:
stage: build
tags:
- dev
before_script:
- docker login -u mathwave -p $DOCKERHUB_PASSWORD
script:
- docker push mathwave/sprint-repo:pizda-bot
.deploy:
before_script:
- docker login -u mathwave -p $DOCKERHUB_PASSWORD
deploy-dev:
extends:
- .deploy
stage: deploy-dev
tags:
- dev
rules:
- if: '$CI_COMMIT_BRANCH == "master"'
when: on_success
- when: manual
script:
- docker stack deploy --with-registry-auth -c ./.deploy/deploy-dev.yaml pizda-bot
deploy-prod:
extends:
- .deploy
stage: deploy-prod
tags:
- prod
only:
- master
when: manual
script:
- docker stack deploy --with-registry-auth -c ./.deploy/deploy-prod.yaml pizda-bot

View File

@@ -2,7 +2,7 @@ from collections import defaultdict
from flask import Flask
from utils.mongo import mongo
from mongo import mongo
app = Flask(__name__)

View File

@@ -1,13 +1,3 @@
import os
stage = os.getenv("STAGE", 'local')
if stage == 'local':
QUEUES_URL = 'localhost:50051'
else:
QUEUES_URL = 'queues-grpc:50051'
class Daemon:
class BaseDaemon:
def execute(self):
raise NotImplemented
raise NotImplementedError

27
daemons/mailbox.py Normal file
View File

@@ -0,0 +1,27 @@
import telebot
import os
from daemons import base
from utils import queues
class Daemon(base.BaseDaemon, queues.TasksHandlerMixin):
def __init__(self):
super().__init__()
self.bot = telebot.TeleBot(os.getenv("TELEGRAM_TOKEN"))
@property
def queue_name(self):
return 'pizda_bot_mailbox'
def execute(self):
self.poll()
def process(self, payload):
body = {
'chat_id': payload['chat_id'],
'text': payload['message'],
}
if payload['action'] == 'reply':
body['reply_to_message_id'] = payload['reply_to']
self.bot.send_message(**body)

16
daemons/poll.py Normal file
View File

@@ -0,0 +1,16 @@
import os
import json
import telebot
from daemons import base
from telebot import types
from utils import queues
class Daemon(base.BaseDaemon):
def execute(self):
bot = telebot.TeleBot(os.getenv("TELEGRAM_TOKEN"))
@bot.message_handler()
def do_action(message: types.Message):
queues.set_task('pizda_bot_worker', message.json, 1)
bot.polling()

View File

@@ -6,9 +6,9 @@ from utils import queues
from telebot.types import Message
import json
from utils.mongo import mongo
from utils.sprint_platform import PlatformClient
from utils.storage import set_values, get_chat_info
from mongo import mongo
from sprint_platform import PlatformClient
from storage import set_values, get_chat_info
security_token = os.getenv("PLATFORM_SECURITY_TOKEN")
stage = os.getenv("STAGE", 'local')
@@ -35,15 +35,11 @@ def get_answers():
return client.get_config('answers')
def get_ignored_users():
return client.get_config('ignored_users')['users']
def get_replies():
return client.get_config('replies')
class Daemon(base.Daemon, queues.TasksHandlerMixin):
class Daemon(base.BaseDaemon, queues.TasksHandlerMixin):
@property
def queue_name(self):
return 'pizda_bot_worker'
@@ -51,31 +47,25 @@ class Daemon(base.Daemon, queues.TasksHandlerMixin):
def execute(self):
self.poll()
def reply(self, text: str, chat_id: int, message_id: int):
def reply(text: str, chat_id: int, message_id: int):
queues.set_task(
'botalka_mailbox',
'pizda_bot_mailbox',
{
'project': 'pizda-bot',
'name': 'telegram-bot',
'body': {
'text': text,
'reply_to_message_id': message_id,
'chat_id': chat_id,
}
'action': 'reply',
'message': text,
'reply_to': message_id,
'chat_id': chat_id
},
1,
)
def send(self, text: str, chat_id: int):
def send(text: str, chat_id: int):
queues.set_task(
'botalka_mailbox',
'pizda_bot_mailbox',
{
'project': 'pizda-bot',
'name': 'telegram-bot',
'body': {
'text': text,
'chat_id': chat_id,
}
'action': 'send',
'message': text,
'chat_id': chat_id
},
1,
)
@@ -123,8 +113,6 @@ class Daemon(base.Daemon, queues.TasksHandlerMixin):
def process(self, payload):
message: Message = Message.de_json(json.dumps(payload))
if not message.text:
return
if message.text.startswith('/'):
self.process_command(message)
return
@@ -155,6 +143,6 @@ class Daemon(base.Daemon, queues.TasksHandlerMixin):
else:
return
ans = get_answers().get(convert_text)
if ans is not None and randrange(1, 101) <= info["probability"] and message.from_user.id not in get_ignored_users():
if ans is not None and randrange(1, 101) <= info["probability"]:
self.reply(ans, message.chat.id, message.message_id)
mongo.inc(message.from_user.username, message.chat.id)

0
launch.json Normal file
View File

5
local_platform.json Normal file
View File

@@ -0,0 +1,5 @@
{
"configs": {},
"experiments": {},
"platform_staff": {}
}

View File

@@ -2,11 +2,14 @@ import sys
arg = sys.argv[-1]
if arg == 'worker':
if arg == 'poll':
from daemons import poll
daemon = poll.Daemon()
elif arg == 'worker':
from daemons import worker
daemon = worker.Daemon()
else:
from daemons.api import app
from api import app
app.run(host="0.0.0.0", port=1238)
daemon.execute()

View File

@@ -1,14 +1,10 @@
import pymongo
import os
MONGO_USER = os.getenv("MONGO_USER", "mongo")
MONGO_PASSWORD = os.getenv("MONGO_PASSWORD", "password")
MONGO_HOST = os.getenv("MONGO_HOST", "localhost")
import settings
class Mongo:
def __init__(self):
url = f"mongodb://{MONGO_USER}:{MONGO_PASSWORD}@{MONGO_HOST}:27017/"
url = f"mongodb://{settings.MONGO_USER}:{settings.MONGO_PASSWORD}@{settings.MONGO_HOST}:27017/"
self.client = pymongo.MongoClient(url)
self.database = self.client.get_database("pizda-bot")
self.chats_collection.create_index([

10
settings.py Normal file
View File

@@ -0,0 +1,10 @@
import os
import sys
import zoneinfo
MONGO_USER = os.getenv("MONGO_USER", "mongo")
MONGO_PASSWORD = os.getenv("MONGO_PASSWORD", "password")
MONGO_HOST = os.getenv("MONGO_HOST", "localhost")
CACHE_SIZE = int(os.getenv("CACHE_SIZE", 1000))
CACHE_TTL = int(os.getenv("CACHE_TTL", 3600))

View File

@@ -14,8 +14,11 @@ class PlatformClient:
self.stage = stage
self.configs = configs
self.experiments = experiments
self.endpoint = 'http://configurator/'
self.fetch_url = urllib.parse.urljoin(self.endpoint, '/api/v1/fetch')
self.endpoint = 'https://platform.sprinthub.ru/'
self.configs_url = urllib.parse.urljoin(self.endpoint, 'configs/get')
self.experiments_url = urllib.parse.urljoin(self.endpoint, 'experiments/get')
self.staff_url = urllib.parse.urljoin(self.endpoint, 'is_staff')
self.fetch_url = urllib.parse.urljoin(self.endpoint, 'fetch')
self.config_storage = {}
self.experiment_storage = {}
self.staff_storage = {}
@@ -40,6 +43,7 @@ class PlatformClient:
try:
response = get(
url,
headers={'X-Security-Token': self.platform_security_token},
params=params
)
if response.status_code == 200:

View File

@@ -1,12 +1,9 @@
from cachetools import TTLCache
import os
from utils.mongo import mongo
import settings
from mongo import mongo
CACHE_SIZE = int(os.getenv("CACHE_SIZE", 1000))
CACHE_TTL = int(os.getenv("CACHE_TTL", 3600))
cache = TTLCache(CACHE_SIZE, CACHE_TTL)
cache = TTLCache(settings.CACHE_SIZE, settings.CACHE_TTL)
def get_chat_info(chat_id: int) -> dict:

View File

@@ -2,7 +2,7 @@ import datetime
import random
from time import sleep
from utils.mongo import mongo
from mongo import mongo
def update():

View File

@@ -1,16 +1,18 @@
from concurrent.futures import ThreadPoolExecutor
import datetime
import json
import os
import zoneinfo
import requests
import time
stage = os.getenv("STAGE", 'local')
if stage == 'local':
QUEUES_URL = 'http://localhost:1239'
if stage == 'development':
QUEUES_URL = 'https://queues.develop.sprinthub.ru'
elif stage == 'production':
QUEUES_URL = 'https://queues.sprinthub.ru'
else:
QUEUES_URL = 'http://queues:1239'
QUEUES_URL = None
token = os.getenv('QUEUES_TOKEN')
class QueuesException(Exception):
@@ -18,54 +20,31 @@ class QueuesException(Exception):
class TasksHandlerMixin:
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.executor = ThreadPoolExecutor(max_workers=1)
def _send_metric(self, start: datetime.datetime, end: datetime.datetime, success: bool):
def send():
requests.post(f'{QUEUES_URL}/api/v1/metric', json={
'service': 'botalka',
'queue': self.queue_name,
'success': success,
'timestamp': start.strftime("%Y-%m-%dT%H:%M:%S") + "Z",
"success": success,
"execution_time_ms": (end - start).microseconds // 1000,
"environment": stage,
})
self.executor.submit(send)
def poll(self):
while True:
if QUEUES_URL is None:
data = {'payload': json.loads(input('Input message: '))}
else:
response = requests.get(f'{QUEUES_URL}/api/v1/take', headers={'queue': self.queue_name, 'X-Queues-Token': token})
if response.status_code == 404:
time.sleep(0.2)
continue
if response.status_code == 403:
raise NotImplemented('QUEUE_TOKEN is incorrect')
data = response.json()
try:
response = requests.get(f'{QUEUES_URL}/api/v1/take', headers={'queue': self.queue_name}).json()
except requests.JSONDecodeError:
print('Unable to decode json')
time.sleep(3)
continue
task = response.get('task')
if not task:
time.sleep(0.2)
continue
start = datetime.datetime.now(zoneinfo.ZoneInfo("Europe/Moscow"))
try:
print(f'process task with id {task["id"]}, attempt {task["attempt"]}')
self.process(task['payload'])
success = True
self.process(data['payload'])
except Exception as exc:
print(f'Error processing message id={task["id"]}, payload={task["payload"]}, exc={exc}')
success = False
end = datetime.datetime.now(zoneinfo.ZoneInfo("Europe/Moscow"))
if success:
try:
resp = requests.post(f'{QUEUES_URL}/api/v1/finish', json={'id': task['id']})
if resp.status_code != 202:
raise QueuesException
print(f'finish task with id {task["id"]}')
except:
print(f'Failed to finish task id={task["id"]}')
self._send_metric(start, end, success)
print(f'Error processing message id={data["id"]}, payload={data["payload"]}, exc={exc}')
continue
if QUEUES_URL is None:
continue
try:
resp = requests.post(f'{QUEUES_URL}/api/v1/finish', json={'id': data['id']}, headers={'X-Queues-Token': token})
if resp.status_code != 202:
raise QueuesException
except:
print(f'Failed to finish task id={data["id"]}')
@property
def queue_name(self):
@@ -76,7 +55,7 @@ class TasksHandlerMixin:
def set_task(queue_name: str, payload: dict, seconds_to_execute: int, delay: int|None = None):
resp = requests.post(f'{QUEUES_URL}/api/v1/put', headers={'queue': queue_name}, json={
resp = requests.post(f'{QUEUES_URL}/api/v1/put', headers={'queue': queue_name, 'X-Queues-Token': token}, json={
'payload': payload,
'seconds_to_execute': seconds_to_execute,
'delay': delay,