Skip to content

Commit

Permalink
enable resiliency by providing FileSystemOrderManager and adding a ne…
Browse files Browse the repository at this point in the history
…w volume
  • Loading branch information
mhewedy committed May 23, 2024
1 parent ace34db commit 4462154
Show file tree
Hide file tree
Showing 3 changed files with 83 additions and 17 deletions.
8 changes: 8 additions & 0 deletions fly.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,15 @@ primary_region = 'cdg'

[env]
PORT = '0'
#CHAT_ID = '' #secret
#BOT_TOKEN = '' #secret
VOLUME_ROOT_FS = '/data'

[[vm]]
size = 'shared-cpu-1x'
memory = "256MB"

[[mounts]]
source = 'lunchy_data'
destination = '/data'
initial_size = '1gb'
32 changes: 15 additions & 17 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,12 @@

import food
import util
from order_manager import FileSystemOrderManager
from selection import UserSelector

bot = BotApp()
userSelector = UserSelector()
orders = {}
order_manager = FileSystemOrderManager(file_path=os.getenv('VOLUME_ROOT_FS', '/tmp') + '/orders.json')


@bot.command(text=True)
Expand All @@ -26,8 +27,8 @@ async def capture():

if food.is_food(message.text):
user = util.current_user(update)
orders[(message.id, user)] = message.text
logging.info(f'adding {message.text} to the order {orders}')
order_manager.add_order(message.id, user, message.text)
logging.info(f'adding {message.text} to the order {order_manager.list_orders()}')

await message.reply_text('تم التعديل' if is_edit else 'تمت الإضافة')
else:
Expand All @@ -45,26 +46,25 @@ async def add_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
return

user = util.current_user(update)
orders[(update.message.id, user)] = order
order_manager.add_order(update.message.id, user, order)
await update.message.reply_text('تمت الإضافة')


@bot.command(name="delete", desc="مسح طلبك")
async def delete_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
user = util.current_user(update)
not_found = True
for (msg_id, u), o in list(orders.items()):
if user == u:
not_found = False
del orders[(msg_id, u)]
deleted_orders = order_manager.delete_order(user)
if deleted_orders:
for (_, _), o in deleted_orders:
await update.message.reply_text(f'تم مسح طلبك "{o}" بنجاح')

if not_found: await update.message.reply_text('لا توجد طلبات')
else:
await update.message.reply_text('لا توجد طلبات')


@bot.command(name="list", desc="عرض الطلبات")
async def list_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
if len(orders) == 0:
orders = order_manager.list_orders()
if not orders:
await update.message.reply_text("لا توجد طلبات")
return

Expand All @@ -84,8 +84,7 @@ async def clear_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text("هذه الخاصية متاحة فقط للأدمن")
return

global orders
orders = {}
order_manager.clear_orders()
msg = "تم مسح جميع الطلبات بنجاح"
if "+selection_history" in context.args:
msg += " و تم مسح جميع اختيارات المستخدمين أيضا"
Expand Down Expand Up @@ -116,8 +115,7 @@ async def send_lunch_headsup(context: ContextTypes.DEFAULT_TYPE, chat_id):
logging.info('today is weekend, job will be suspended')
return

global orders
orders = {}
order_manager.clear_orders()
await context.bot.send_message(chat_id, text="يلا يا شباب أبدأو ضيفو طلابتكم")


Expand All @@ -127,7 +125,7 @@ async def send_lunch_selection(context: ContextTypes.DEFAULT_TYPE, chat_id):


async def select_user(context: ContextTypes.DEFAULT_TYPE, chat_id):
users = [user for (_, user), _ in orders.items()]
users = [user for (_, user), _ in order_manager.list_orders().items()]
if users:
uid, u = userSelector.select(users)
mention_text = f"<a href='tg://user?id={uid}'>{u}</a>"
Expand Down
60 changes: 60 additions & 0 deletions order_manager.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import ast
import json
import logging
from abc import ABC
from pathlib import Path


class OrderManager(ABC):
def __init__(self):
self.orders = {}

def add_order(self, message_id, user, order):
self.orders[(message_id, user)] = order

def delete_order(self, user):
deleted_orders = [(key, self.orders[key]) for key in list(self.orders) if key[1] == user]
for key, _ in deleted_orders:
del self.orders[key]
return deleted_orders

def list_orders(self):
return self.orders

def clear_orders(self):
self.orders = {}


class InMemoryOrderManager(OrderManager):
pass


class FileSystemOrderManager(OrderManager):
def __init__(self, file_path):
super().__init__()
self.file_path = Path(file_path)
logging.info('loading orders from: {}'.format(self.file_path))
if self.file_path.exists():
with open(self.file_path, 'r') as file:
self.orders = {ast.literal_eval(k): v for k, v in json.load(file).items()}
logging.info('loaded orders {}'.format(self.orders))
else:
logging.error('orders file does not exist, creating one...')
self._save_to_file()

def add_order(self, message_id, user, order):
super().add_order(message_id, user, order)
self._save_to_file()

def delete_order(self, user):
deleted_orders = super().delete_order(user)
self._save_to_file()
return deleted_orders

def clear_orders(self):
super().clear_orders()
self._save_to_file()

def _save_to_file(self):
with open(self.file_path, 'w') as file:
json.dump({str(k): v for k, v in self.orders.items()}, file)

0 comments on commit 4462154

Please sign in to comment.