Compare commits

...

23 Commits

Author SHA1 Message Date
2f3d785aec Merge pull request 'master' (#9) from master into prod
Reviewed-on: #9
2025-09-14 09:45:16 +03:00
f165ee6f30 Update .deploy/deploy-prod.yaml
All checks were successful
Deploy Prod / Build (pull_request) Successful in 5s
Deploy Prod / Push (pull_request) Successful in 9s
Deploy Prod / Deploy prod (pull_request) Successful in 13s
2025-09-14 09:45:04 +03:00
8cdf0cbd8d Update .deploy/deploy-prod.yaml
All checks were successful
Deploy Dev / Build (pull_request) Successful in 1m20s
Deploy Dev / Push (pull_request) Successful in 22s
Deploy Dev / Deploy dev (pull_request) Successful in 29s
2025-09-12 20:42:31 +03:00
6a1f2d3d09 Update .deploy/deploy-dev.yaml 2025-09-12 20:42:09 +03:00
Egor Matveev
6509e58b6e fix
All checks were successful
Deploy Dev / Build (pull_request) Successful in 6s
Deploy Dev / Push (pull_request) Successful in 12s
Deploy Dev / Deploy dev (pull_request) Successful in 19s
2025-07-08 02:05:25 +04:00
Egor Matveev
28df4aef54 fix
All checks were successful
Deploy Dev / Build (pull_request) Successful in 7s
Deploy Dev / Push (pull_request) Successful in 13s
Deploy Dev / Deploy dev (pull_request) Successful in 18s
2025-07-08 01:30:10 +04:00
Egor Matveev
c15e950e02 fix
All checks were successful
Deploy Dev / Build (pull_request) Successful in 6s
Deploy Dev / Push (pull_request) Successful in 13s
Deploy Dev / Deploy dev (pull_request) Successful in 20s
2025-07-08 01:25:34 +04:00
Egor Matveev
10f86f2f99 fix
All checks were successful
Deploy Dev / Build (pull_request) Successful in 6s
Deploy Dev / Push (pull_request) Successful in 13s
Deploy Dev / Deploy dev (pull_request) Successful in 36s
2025-07-08 01:21:29 +04:00
Egor Matveev
556a45b0d4 fix
Some checks failed
Deploy Dev / Build (pull_request) Successful in 7s
Deploy Dev / Push (pull_request) Successful in 13s
Deploy Dev / Deploy dev (pull_request) Failing after 4s
2025-07-08 01:19:01 +04:00
Egor Matveev
d806cd89c0 Merge branch 'master' of https://gitea.sprinthub.ru/self/b-jokes
Some checks failed
Deploy Dev / Build (pull_request) Successful in 1m12s
Deploy Dev / Push (pull_request) Successful in 21s
Deploy Dev / Deploy dev (pull_request) Failing after 3s
2025-07-08 01:14:09 +04:00
Egor Matveev
3a35c77419 fix 2025-07-08 01:13:58 +04:00
2a1c13e351 Merge pull request 'Update .deploy/deploy-prod.yaml' (#1) from master into prod
Reviewed-on: #1
2024-12-02 15:23:50 +03:00
8a12d3b9ba Update .deploy/deploy-prod.yaml
All checks were successful
Deploy Prod / Build (pull_request) Successful in 15s
Deploy Prod / Push (pull_request) Successful in 10s
Deploy Prod / Deploy prod (pull_request) Successful in 10s
2024-12-02 15:23:18 +03:00
f68533fbef add 2024-10-11 07:31:51 +03:00
59bc677f0d Update deploy-prod.yaml 2023-07-31 06:19:20 +00:00
Administrator
b51bd5b03e common infra nginx 2022-10-19 19:00:38 +03:00
Administrator
ed9c96ba9e common infra nginx 2022-10-18 20:21:23 +03:00
Administrator
729b16a6fb b jokes driver 2022-10-18 20:06:59 +03:00
Administrator
83556b2261 deploy no network 2022-10-18 18:56:00 +03:00
Administrator
84b70a07b4 debug 2022-10-11 15:32:15 +03:00
Administrator
4b8950242a check sentry 2022-10-11 15:31:16 +03:00
Administrator
5be090e4bc sentry flask 2022-10-11 15:04:29 +03:00
Administrator
903a596996 fix yaml 2022-10-11 14:56:00 +03:00
11 changed files with 342 additions and 13 deletions

View File

@@ -7,7 +7,7 @@ services:
image: mathwave/sprint-repo:b-jokes-nginx
networks:
- b-jokes-net
- b-jokes-nginx
- common-infra-nginx
deploy:
mode: replicated
restart_policy:
@@ -21,7 +21,7 @@ services:
networks:
- b-jokes-net
environment:
MONGO_HOST: "mongo.develop.sprinthub.ru"
MONGO_HOST: "mongo.dev.chocomarsh.com"
MONGO_PASSWORD: $MONGO_PASSWORD_DEV
command: api
deploy:
@@ -35,7 +35,7 @@ services:
poll:
image: mathwave/sprint-repo:b-jokes
environment:
MONGO_HOST: "mongo.develop.sprinthub.ru"
MONGO_HOST: "mongo.dev.chocomarsh.com"
MONGO_PASSWORD: $MONGO_PASSWORD_DEV
command: poll
deploy:
@@ -46,8 +46,30 @@ services:
parallelism: 1
order: start-first
bot:
image: mathwave/sprint-repo:b-jokes
environment:
MONGO_HOST: "mongo.dev.chocomarsh.com"
MONGO_PASSWORD: $MONGO_PASSWORD_DEV
STAGE: "development"
command: bot
networks:
- configurator
- queues-development
deploy:
mode: replicated
restart_policy:
condition: any
update_config:
parallelism: 1
order: start-first
networks:
b-jokes-net:
driver: overlay
b-jokes-nginx:
common-infra-nginx:
external: true
configurator:
external: true
queues-development:
external: true

View File

@@ -7,7 +7,7 @@ services:
image: mathwave/sprint-repo:b-jokes-nginx
networks:
- b-jokes-net
- b-jokes-nginx
- common-infra-nginx
deploy:
mode: replicated
restart_policy:
@@ -21,9 +21,9 @@ services:
networks:
- b-jokes-net
environment:
MONGO_HOST: "mongo.sprinthub.ru"
MONGO_HOST: "mongo.chocomarsh.com"
MONGO_PASSWORD: $MONGO_PASSWORD_PROD
DEBUG: false
DEBUG: "false"
command: api
deploy:
mode: replicated
@@ -36,9 +36,9 @@ services:
poll:
image: mathwave/sprint-repo:b-jokes
environment:
MONGO_HOST: "mongo.sprinthub.ru"
MONGO_HOST: "mongo.chocomarsh.com"
MONGO_PASSWORD: $MONGO_PASSWORD_PROD
DEBUG: false
DEBUG: "false"
command: poll
deploy:
mode: replicated
@@ -51,5 +51,5 @@ services:
networks:
b-jokes-net:
driver: overlay
b-jokes-nginx:
common-infra-nginx:
external: true

View File

@@ -0,0 +1,47 @@
name: Deploy Dev
on:
pull_request:
branches:
- dev
types: [closed]
jobs:
build:
name: Build
runs-on: [ dev ]
steps:
- name: login
run: docker login -u mathwave -p ${{ secrets.DOCKERHUB_PASSWORD }}
- name: checkout
uses: actions/checkout@v4
with:
ref: dev
- name: build
run: docker build -t mathwave/sprint-repo:b-jokes .
- name: build-nginx
run: docker build -t mathwave/sprint-repo:b-jokes-nginx nginx
push:
name: Push
runs-on: [ dev ]
needs: build
steps:
- name: push
run: docker push mathwave/sprint-repo:b-jokes
- name: push-nginx
run: docker push mathwave/sprint-repo:b-jokes-nginx
deploy-dev:
name: Deploy dev
runs-on: [prod]
needs: push
steps:
- name: login
run: docker login -u mathwave -p ${{ secrets.DOCKERHUB_PASSWORD }}
- name: checkout
uses: actions/checkout@v4
with:
ref: dev
- name: deploy
env:
MONGO_PASSWORD_DEV: ${{ secrets.MONGO_PASSWORD_DEV }}
run: docker stack deploy --with-registry-auth -c ./.deploy/deploy-dev.yaml b-jokes-development

View File

@@ -0,0 +1,43 @@
name: Deploy Prod
on:
pull_request:
branches:
- prod
types: [closed]
jobs:
build:
name: Build
runs-on: [ dev ]
steps:
- name: login
run: docker login -u mathwave -p ${{ secrets.DOCKERHUB_PASSWORD }}
- name: checkout
uses: actions/checkout@v4
with:
ref: prod
- name: build
run: docker build -t mathwave/sprint-repo:b-jokes .
push:
name: Push
runs-on: [ dev ]
needs: build
steps:
- name: push
run: docker push mathwave/sprint-repo:b-jokes
deploy-prod:
name: Deploy prod
runs-on: [prod]
needs: push
steps:
- name: login
run: docker login -u mathwave -p ${{ secrets.DOCKERHUB_PASSWORD }}
- name: checkout
uses: actions/checkout@v4
with:
ref: prod
- name: deploy
env:
MONGO_PASSWORD_PROD: ${{ secrets.MONGO_PASSWORD_PROD }}
run: docker stack deploy --with-registry-auth -c ./.deploy/deploy-prod.yaml b-jokes

View File

@@ -18,7 +18,6 @@ build:
.deploy:
before_script:
- docker login -u mathwave -p $DOCKERHUB_PASSWORD
- docker network create -d overlay --attachable b-jokes-nginx || true
deploy-dev:
extends:

View File

@@ -12,5 +12,7 @@ if arg == "poll":
jokes.poll_jokes()
elif arg == "api":
main.run()
elif arg == "bot":
main.bot()
else:
raise NotImplementedError("No arg specified!")

84
helpers/configurator.py Normal file
View File

@@ -0,0 +1,84 @@
import json
import urllib.parse
from threading import Thread
from time import sleep
from requests import get
class ConfiguratorClient:
def __init__(self, app_name: str, stage: str, need_poll: bool = True):
self.app_name = app_name
self.stage = stage
self.endpoint = 'http://configurator/'
self.fetch_url = urllib.parse.urljoin(self.endpoint, '/api/v1/fetch')
self.config_storage = {}
self.experiment_storage = {}
self.staff_storage = {}
self.poll_data()
if need_poll:
self.poll_data_in_thread()
def poll_data_in_thread(self):
def inner():
while True:
sleep(30)
self.fetch()
Thread(target=inner, daemon=True).start()
def poll_data(self):
self.fetch(with_exception=True)
def request_with_retries(self, url, params, with_exception=False, retries_count=3):
exception_to_throw = None
for _ in range(retries_count):
try:
response = get(
url,
params=params
)
if response.status_code == 200:
return response.json()
print(f'Failed to request {url}, status_code={response.status_code}')
exception_to_throw = Exception('Not 200 status')
except Exception as exc:
print(exc)
exception_to_throw = exc
sleep(1)
print(f'Failed fetching with retries: {url}, {params}')
if with_exception:
raise exception_to_throw
def fetch(self, with_exception=False):
if self.stage == 'local':
local_platform = json.loads(open('local_platform.json', 'r').read())
self.config_storage = local_platform['configs']
self.experiment_storage = local_platform['experiments']
self.staff_storage = {
key: set(value)
for key, value in local_platform['platform_staff'].items()
}
return
response_data = self.request_with_retries(self.fetch_url, {
'project': self.app_name,
'stage': self.stage,
}, with_exception)
self.config_storage = response_data['configs']
self.experiment_storage = response_data['experiments']
self.staff_storage = {
key: set(value)
for key, value in response_data['platform_staff'].items()
}
def is_staff(self, **kwargs):
for key, value in kwargs.items():
if value in self.staff_storage[key]:
return True
return False
def get_config(self, name):
return self.config_storage[name]
def get_experiment(self, name):
return self.experiment_storage[name]

85
helpers/queues.py Normal file
View File

@@ -0,0 +1,85 @@
from concurrent.futures import ThreadPoolExecutor
import datetime
import os
import zoneinfo
import requests
import time
stage = os.getenv("STAGE", 'local')
if stage == 'local':
QUEUES_URL = 'http://localhost:1239'
else:
QUEUES_URL = 'http://queues:1239'
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': 'b-jokes',
'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:
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
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)
@property
def queue_name(self):
raise NotImplemented
def process(self, payload):
raise NotImplemented
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={
'payload': payload,
'seconds_to_execute': seconds_to_execute,
'delay': delay,
})
if resp.status_code != 202:
raise QueuesException

44
main.py
View File

@@ -1,5 +1,10 @@
import os
from flask import Flask, request, make_response
from helpers.configurator import ConfiguratorClient
from helpers.jokes import get_random
from helpers.queues import TasksHandlerMixin, set_task
import settings
from helpers.events import events
from processor import Processor
@@ -32,4 +37,41 @@ def run():
def today():
return events.today_json()
app.run(host="0.0.0.0", port=8000)
@app.route('/check_sentry')
def check_sentry():
a = 1 / 0
app.run(host="0.0.0.0", port=8000, debug=settings.DEBUG)
def bot():
configurator = ConfiguratorClient("b-jokes", os.getenv("STAGE", "local"))
class Bot(TasksHandlerMixin):
@property
def queue_name(self):
return "b_jokes_worker"
def process(self, payload):
text = payload.get('text')
if not text:
return
text = text.lower()
for word in configurator.get_config('words'):
if word in text:
mes = 'Держи шутку!\n' + get_random()
set_task(
"botalka_mailbox",
{
'project': 'b-jokes',
'name': 'telegram-bot',
'body': {
'text': mes,
'reply_to_message_id': payload['message_id'],
'chat_id': payload['chat']['id'],
}
},
1
)
return
Bot().poll()

View File

@@ -1,3 +1,4 @@
blinker==1.5
certifi==2022.9.24
charset-normalizer==2.1.1
click==8.1.3

View File

@@ -2,6 +2,7 @@ import logging
import os
import sentry_sdk
from sentry_sdk.integrations.flask import FlaskIntegration
MONGO_USER = os.getenv("MONGO_USER", "mongo")
MONGO_PASSWORD = os.getenv("MONGO_PASSWORD", "password")
@@ -14,7 +15,10 @@ def setup():
if not DEBUG:
sentry_sdk.init(
dsn=f"https://{os.getenv('SENTRY_TOKEN')}@o1155463.ingest.sentry.io/4503964727050240",
traces_sample_rate=1.0
traces_sample_rate=1.0,
integrations=[
FlaskIntegration(),
]
)
logging.basicConfig(level=logging.INFO)
logging.info("app is set up")