From 2ed8e1112c5d96512467d53c0f1c55f32767994f Mon Sep 17 00:00:00 2001 From: anor Date: Wed, 4 Feb 2026 16:51:33 +1000 Subject: [PATCH] Initial commit: Test GLM project --- .DS_Store | Bin 0 -> 14340 bytes .coverage | Bin 0 -> 53248 bytes README.md | 115 +++ __pycache__/api_client.cpython-311.pyc | Bin 0 -> 10880 bytes ...st_api_client.cpython-311-pytest-9.0.2.pyc | Bin 0 -> 45832 bytes ai_coder_1/.DS_Store | Bin 0 -> 6148 bytes ai_coder_1/PROMPT.md | 139 ++++ ai_coder_1/result.json | 17 + ai_coder_1/result.txt | 4 + ai_coder_1/scripts/load_tasks.py | 197 +++++ ai_coder_1/start_time.txt | 1 + ai_coder_1/subtasks/Decomp-001-01.md | 83 ++ ai_coder_1/subtasks/Decomp-001-02.md | 80 ++ ai_coder_1/subtasks/Decomp-001-03.md | 91 ++ ai_coder_1/subtasks/Decomp-001-04.md | 90 ++ ai_coder_1/subtasks/Decomp-001-05.md | 119 +++ ai_coder_1/subtasks/Decomp-001-06.md | 91 ++ ai_coder_1/subtasks/Decomp-001-07.md | 110 +++ ai_coder_1/subtasks/Decomp-001-08.md | 144 ++++ ai_coder_1/subtasks/Decomp-001-09.md | 223 +++++ ai_coder_1/subtasks/Decomp-001-10.md | 268 ++++++ ai_coder_1/subtasks/Decomp-001-11.md | 363 ++++++++ ai_coder_1/subtasks/Decomp-002-01.md | 248 ++++++ ai_coder_1/subtasks/Decomp-002-02.md | 366 ++++++++ ai_coder_1/subtasks/Decomp-002-03.md | 392 +++++++++ ai_coder_1/subtasks/Decomp-002-04.md | 376 +++++++++ ai_coder_1/subtasks/Decomp-002-05.md | 366 ++++++++ ai_coder_1/subtasks/Decomp-002-06.md | 370 +++++++++ ai_coder_1/subtasks/Decomp-002-07.md | 362 ++++++++ ai_coder_1/subtasks/Decomp-002-08.md | 346 ++++++++ ai_coder_1/subtasks/Decomp-003-01.md | 272 ++++++ ai_coder_1/subtasks/Decomp-003-02.md | 437 ++++++++++ ai_coder_1/subtasks/Decomp-003-03.md | 476 +++++++++++ ai_coder_1/subtasks/Decomp-003-04.md | 424 ++++++++++ ai_coder_1/subtasks/Decomp-003-05.md | 478 +++++++++++ ai_coder_1/subtasks/Decomp-003-06.md | 512 ++++++++++++ ai_coder_1/subtasks/Decomp-003-07.md | 395 +++++++++ ai_coder_1/subtasks/Decomp-003-08.md | 515 ++++++++++++ ai_coder_1/subtasks/Decomp-003-09.md | 493 +++++++++++ ai_coder_1/subtasks/Decomp-004-01.md | 522 ++++++++++++ ai_coder_1/subtasks/Decomp-004-02.md | 544 ++++++++++++ ai_coder_1/subtasks/Decomp-004-03.md | 464 +++++++++++ ai_coder_1/subtasks/Decomp-004-04.md | 674 +++++++++++++++ ai_coder_1/subtasks/Decomp-004-05.md | 547 ++++++++++++ ai_coder_1/subtasks/Decomp-004-06.md | 592 +++++++++++++ ai_coder_1/subtasks/Decomp-004-07.md | 613 ++++++++++++++ ai_coder_1/subtasks/Decomp-004-08.md | 638 ++++++++++++++ ai_coder_1/subtasks/Decomp-004-09.md | 654 +++++++++++++++ ai_coder_1/subtasks/Decomp-005-01.md | 445 ++++++++++ ai_coder_1/subtasks/Decomp-005-02.md | 648 +++++++++++++++ ai_coder_1/subtasks/Decomp-005-03.md | 709 ++++++++++++++++ ai_coder_1/subtasks/Decomp-005-04.md | 654 +++++++++++++++ ai_coder_1/subtasks/Decomp-005-05.md | 780 ++++++++++++++++++ ai_coder_1/subtasks/Decomp-005-06.md | 594 +++++++++++++ ai_coder_1/subtasks/Decomp-005-07.md | 637 ++++++++++++++ ai_coder_1/subtasks/Decomp-005-08.md | 694 ++++++++++++++++ ai_coder_1/subtasks/Decomp-005-09.md | 635 ++++++++++++++ ai_coder_1/tasks.json | 172 ++++ ai_coder_2/.DS_Store | Bin 0 -> 6148 bytes ai_coder_2/PROMPT.md | 139 ++++ ai_coder_2/result.json | 20 + ai_coder_2/result.txt | 18 + ai_coder_2/scripts/load_tasks.py | 197 +++++ ai_coder_2/start_time.txt | 1 + ai_coder_2/subtasks/.DS_Store | Bin 0 -> 6148 bytes ai_coder_2/subtasks/Decomp/001-01.md | 87 ++ ai_coder_2/subtasks/Decomp/001-02.md | 73 ++ ai_coder_2/subtasks/Decomp/001-03.md | 101 +++ ai_coder_2/subtasks/Decomp/001-04.md | 114 +++ ai_coder_2/subtasks/Decomp/001-05.md | 159 ++++ ai_coder_2/subtasks/Decomp/001-06.md | 127 +++ ai_coder_2/subtasks/Decomp/001-07.md | 130 +++ ai_coder_2/subtasks/Decomp/001-08.md | 225 +++++ ai_coder_2/subtasks/Decomp/001-09.md | 182 ++++ ai_coder_2/subtasks/Decomp/001-10.md | 196 +++++ ai_coder_2/subtasks/Decomp/001-11.md | 215 +++++ ai_coder_2/subtasks/Decomp/001-12.md | 276 +++++++ ai_coder_2/tasks.json | 172 ++++ ai_judge/.DS_Store | Bin 0 -> 6148 bytes ai_judge/PROMPT.md | 193 +++++ api_client.py | 209 +++++ pytest.ini | 24 + requirements.txt | 14 + tasks.json | 109 +++ test_api_client.py | 351 ++++++++ 85 files changed, 23511 insertions(+) create mode 100644 .DS_Store create mode 100644 .coverage create mode 100644 README.md create mode 100644 __pycache__/api_client.cpython-311.pyc create mode 100644 __pycache__/test_api_client.cpython-311-pytest-9.0.2.pyc create mode 100644 ai_coder_1/.DS_Store create mode 100644 ai_coder_1/PROMPT.md create mode 100644 ai_coder_1/result.json create mode 100644 ai_coder_1/result.txt create mode 100644 ai_coder_1/scripts/load_tasks.py create mode 100644 ai_coder_1/start_time.txt create mode 100644 ai_coder_1/subtasks/Decomp-001-01.md create mode 100644 ai_coder_1/subtasks/Decomp-001-02.md create mode 100644 ai_coder_1/subtasks/Decomp-001-03.md create mode 100644 ai_coder_1/subtasks/Decomp-001-04.md create mode 100644 ai_coder_1/subtasks/Decomp-001-05.md create mode 100644 ai_coder_1/subtasks/Decomp-001-06.md create mode 100644 ai_coder_1/subtasks/Decomp-001-07.md create mode 100644 ai_coder_1/subtasks/Decomp-001-08.md create mode 100644 ai_coder_1/subtasks/Decomp-001-09.md create mode 100644 ai_coder_1/subtasks/Decomp-001-10.md create mode 100644 ai_coder_1/subtasks/Decomp-001-11.md create mode 100644 ai_coder_1/subtasks/Decomp-002-01.md create mode 100644 ai_coder_1/subtasks/Decomp-002-02.md create mode 100644 ai_coder_1/subtasks/Decomp-002-03.md create mode 100644 ai_coder_1/subtasks/Decomp-002-04.md create mode 100644 ai_coder_1/subtasks/Decomp-002-05.md create mode 100644 ai_coder_1/subtasks/Decomp-002-06.md create mode 100644 ai_coder_1/subtasks/Decomp-002-07.md create mode 100644 ai_coder_1/subtasks/Decomp-002-08.md create mode 100644 ai_coder_1/subtasks/Decomp-003-01.md create mode 100644 ai_coder_1/subtasks/Decomp-003-02.md create mode 100644 ai_coder_1/subtasks/Decomp-003-03.md create mode 100644 ai_coder_1/subtasks/Decomp-003-04.md create mode 100644 ai_coder_1/subtasks/Decomp-003-05.md create mode 100644 ai_coder_1/subtasks/Decomp-003-06.md create mode 100644 ai_coder_1/subtasks/Decomp-003-07.md create mode 100644 ai_coder_1/subtasks/Decomp-003-08.md create mode 100644 ai_coder_1/subtasks/Decomp-003-09.md create mode 100644 ai_coder_1/subtasks/Decomp-004-01.md create mode 100644 ai_coder_1/subtasks/Decomp-004-02.md create mode 100644 ai_coder_1/subtasks/Decomp-004-03.md create mode 100644 ai_coder_1/subtasks/Decomp-004-04.md create mode 100644 ai_coder_1/subtasks/Decomp-004-05.md create mode 100644 ai_coder_1/subtasks/Decomp-004-06.md create mode 100644 ai_coder_1/subtasks/Decomp-004-07.md create mode 100644 ai_coder_1/subtasks/Decomp-004-08.md create mode 100644 ai_coder_1/subtasks/Decomp-004-09.md create mode 100644 ai_coder_1/subtasks/Decomp-005-01.md create mode 100644 ai_coder_1/subtasks/Decomp-005-02.md create mode 100644 ai_coder_1/subtasks/Decomp-005-03.md create mode 100644 ai_coder_1/subtasks/Decomp-005-04.md create mode 100644 ai_coder_1/subtasks/Decomp-005-05.md create mode 100644 ai_coder_1/subtasks/Decomp-005-06.md create mode 100644 ai_coder_1/subtasks/Decomp-005-07.md create mode 100644 ai_coder_1/subtasks/Decomp-005-08.md create mode 100644 ai_coder_1/subtasks/Decomp-005-09.md create mode 100644 ai_coder_1/tasks.json create mode 100644 ai_coder_2/.DS_Store create mode 100644 ai_coder_2/PROMPT.md create mode 100644 ai_coder_2/result.json create mode 100644 ai_coder_2/result.txt create mode 100644 ai_coder_2/scripts/load_tasks.py create mode 100644 ai_coder_2/start_time.txt create mode 100644 ai_coder_2/subtasks/.DS_Store create mode 100644 ai_coder_2/subtasks/Decomp/001-01.md create mode 100644 ai_coder_2/subtasks/Decomp/001-02.md create mode 100644 ai_coder_2/subtasks/Decomp/001-03.md create mode 100644 ai_coder_2/subtasks/Decomp/001-04.md create mode 100644 ai_coder_2/subtasks/Decomp/001-05.md create mode 100644 ai_coder_2/subtasks/Decomp/001-06.md create mode 100644 ai_coder_2/subtasks/Decomp/001-07.md create mode 100644 ai_coder_2/subtasks/Decomp/001-08.md create mode 100644 ai_coder_2/subtasks/Decomp/001-09.md create mode 100644 ai_coder_2/subtasks/Decomp/001-10.md create mode 100644 ai_coder_2/subtasks/Decomp/001-11.md create mode 100644 ai_coder_2/subtasks/Decomp/001-12.md create mode 100644 ai_coder_2/tasks.json create mode 100644 ai_judge/.DS_Store create mode 100644 ai_judge/PROMPT.md create mode 100644 api_client.py create mode 100644 pytest.ini create mode 100644 requirements.txt create mode 100644 tasks.json create mode 100644 test_api_client.py diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..8a4660b1c8dc9365d4431a21003ffd4f68cae8a8 GIT binary patch literal 14340 zcmeHNX^a#_6t34SOgFnNy~{Zq+OTrE!VIi}vaquU$h85Pg}uOWX1dvJ>Fr*pduBOh zjRrO*8ZagVj8{BCZ7=bl_aTZ3*ON7Kol9)sx zDoGV^7glgsMdiydjwW%U<;llLI1^17x@mM%zFxDrIiZ^g%=4YG1Lu&kzz|>vFa#I^ z3;~9~-$#J1y%_j%m$H;0zz|>vwsIekLMg;IR}jr%JH*F;twIn_{_SIKSi zhvV(*@s01k4S4Sm;SQ3I~4i^xDjO|M+E{xpggcO+GF-d z?YNz`8sn)hT582fC$jl?VzZ|9$E0yhreVi5LrpmXnxZ1hmNv~$%>G6*Z77x_8+985 zffr)Zl-;|-i*8(8BQLD2-CHB?4u_V6Yvgb!v}o^MfgfMJVClx#cD>gy?{^?1;Jw<2 z=$3Qo1DGqAS|0pl{#`|RtW1+T{ShtM>3`-;pBF}#SBO`MZS55uon2yQd`GLg!;WgZ z)R;8JLL62nO=Ck!&EWjolBS;SHLRFanT+env>vzB23@DjSXV_^*7w<(X;_=pl!cUb zkxZGozQMFK+R)K%`+Co7YVWknl-=Zv(5~U2t`1V#Qa7qNl9o}MaXhO!GS5XsI5uX| zv>CH&!Z+Sr-@Llz)*-2~YOE+unAn!lEG?m{9dRqE8j5CgZ|c_+yQdSMieYQpG&Lm% zm9VPSi1(^PQdQ;H;N;*`UaIEX(+Ta)v}W%d8e3TdHe&aSe^18TXukTY09GuQQ7`$Z_w!PbF z^~6)^`hK+1Z2dZ(cOEC!Q=t`#W}DbZr#>^df#*ADcMXa{r%_cYZHxwkF-g*ljD|je z&&_oW>0_Q3#^vnM%|LawqWZ-46HeX%wmK4W8w51kYsfrON191H=_UKfAUR5&CdbH| zQc@^TIi5g#(URrCrdfo z>NOQ>*R}koobA&w)WpV(pD=OK^jX)1YHwQJl(S6NlC$RPcM8WB@_fkg1;;=xHsRpp zDO0D3*T|dDS=1dDJ8#yhr2usbeu#3<5U-V`k?2Zpake;DmPQHETDMpu&zB_*y_6rC zI(bS^l;gy58$<(0BTz3wtt{}<$2 z@&h>!fYv`2CZWyOzzwhzR-mm%VH0ddd+&rKsIU!fUV{|cd>Z;;2iy(!z`c&$AB02j zAUp(*z@zXOJdv~g7vLp04zI%-@Ftvu_u&Kh5KhBK@G*M8_i!G5nhMa}3cgxw7 zqhHkp7Vclkf8P`MX{Ec87vcMJ6~7c;-U?1O(7_A(^8W(B_5kT2Hoi-A=SM>(ZxQ4I zZG{|uou?Z&#}~RfU(`>p`KQLEx$^Yo+z%hBGz$y?h5$o=A;1v$uOUFc>dVM{+$?Lv z&Rb5&^Nam${)LqOe?R0dq&Zpt5?ZW1Z}Ei3DNZ7e+edcdg02z^Q+j(KjeAeP-OhYip70j=OZ4y8_OD6g=}%5m{mW6~m@|W%-n1rP_s<7QbNcl@-S+A?p57(; z_3J!5cfP(qQhkdZ6IS;}QOODXEP=y2>j zC40!o&QpdvO}z5YQ;J%-{}W)}J%e-Bl>R#s_J05j$D6nOS4edEXMrKW5MT%}1Q-Gi z0wY}de=rI^F;uU`bD_a)d}iYw|aMbVuR+yDD68U6G7|33hZ C|Gg0a literal 0 HcmV?d00001 diff --git a/.coverage b/.coverage new file mode 100644 index 0000000000000000000000000000000000000000..85f72fcb949008ecb9706e0ef5b1f1c544fc80e1 GIT binary patch literal 53248 zcmeI)&5ILf90%~3%$k^N!dPSp%VPJrwCmz-VrW6y3U+OmBDJWkcqw#zGI_E)nwg37 zqPx%{s|BIpxrLVg0p5D+Ns2x9Q0UzrrH5Whp`ZtUzj?`vZe%TjyX|*KvXhzTdFJaN4IcpxL5Qnqu ziy}~66)4YEVH(9@r?XgDym`G+svkV4-%?4PWMI>6daO2dU|5w?T`I`-gAPaE4y0$V zt8hukK@Dx6;@pVR+6KPcjC|2^yri05=tPe13ALf@I8vQ$E4ajH`9^r7wV|>ua)mCY zIkRhx=nOM&lQT=6W$sdNo}aT0GxDV=a}u)`yKN%B6uW(H9LkYiIPxduoRl~6v&!zc zZMJF4VSUG%GbiU3O>@Pbb0t=T#$OV{oJ&bHJby`WC8!6yHeIa0bx_x+SE`NhN{?P| zSu&3N43z z*`Lx_7s^|5n`tyZRhlZ* zXJ+)RbVTsH#P@w;mEa@8A@IaPu=DWyGFlf;$Igc-@P&QF`a3g|0_PB{7C#nmep*OE zzBQZZyEN(Z-53j*j|@ZpP;D+>l|7nG`qBw#$kH5~t^k4)b|fX1Z9k5Z{>x93?#XM< zFy6F);q%;{QY|LQX?UOY!_c8+m6xsX?fj@%SeGHsLg9jF`+iSJFI^ib$ElF6>4YMQ z;ptWB#ITHTlgn7Ux{$<_FD^XIpQk~Wk1yJBUFmhQ^@^9_v{ah=d2sS|(n*9eiUk^! zAq~+d%FGMR&hm_vm*41<376{1PCDGVQASF!tdUBl=dH4aRhyu|itZU73fSJuQrNk|$0M z`^y=caOu^~Xg^`Q5e|NuUV$gKv<2I#LY^vnty5X#H~6~wP@@|*2tWV=5P$##AOHaf zKmY;|fB*#kdjf`D&`bROzhM5ZnSas)HV8lf0uX=z1Rwwb2tWV=5P$##_M||yU>q{@ zZ+IL%pc`|u*>?brHCjg-M=MmTg84u*ADDmd$qFK92tWV=5P$##AOHafKmY;|fB*yr z0#)OXp8p%5P%-Ap*?$4j@BiP^%zJ~R*nt29AOHafKmY;|fB*y_009ULP> z`uYET&Ah+s!b3n1fB*y_009U<00Izz00bZa0SN3&U|ydpmrs8F^)K4l6WZM~f6V-N z_tl>+ef!rB{%`lcxpT)e($D`NYUab86^K+2fB*y_009U<00Izz00bZa0SN3Vfhqde zK=S#&c3@A%jbI@F0SG_<0uX=z1Rwwb2tWV=5O_`j{`?>B|DO{L$sqs%2tWV=5P$## tAOHafKmY=JOaQXB literal 0 HcmV?d00001 diff --git a/README.md b/README.md new file mode 100644 index 0000000..18aec1e --- /dev/null +++ b/README.md @@ -0,0 +1,115 @@ +# AI Decomposition Comparison Framework + +Фреймворк для сравнения Architect LLM (Opus) vs Coder LLM (Sonet) на задачах декомпозиции сложных систем. + +## Концепция + +``` +Architect (Opus 4.5) Coder (Sonet 4.5) + ↓ ↓ +Большая задача → Декомпозиция → Реализация компонентов + ↓ ↓ +Component specs ────────────────→ Код + тесты + ↓ +Interface design +``` + +## Структура + +``` +. +├── ai_architect/ # Architect (Opus) +│ ├── PROMPT.md # Инструкции для декомпозиции +│ ├── scripts/ +│ │ └── load_tasks.py # Загрузка задач +│ ├── decomposition/ # Планы декомпозиции +│ │ └── .md +│ └── specs/ # Спецификации компонентов +│ └── .md +│ +├── ai_coder_1/ # Coder 1 (Sonet) +│ ├── PROMPT.md # Инструкции для реализации +│ ├── solutions/ # Реализация компонентов +│ │ └── .py +│ └── tests/ # Тесты компонентов +│ └── test_.py +│ +├── ai_coder_2/ # Coder 2 (для сравнения) +│ └── (аналогично ai_coder_1) +│ +└── ai_judge/ # Judge (оценка) + └── PROMPT.md # Критерии оценки +``` + +## Задачи (5 complex systems) + +| ID | Система | Сложность | +|----|---------|-----------| +| Decomp/001 | URL Shortener (bit.ly) | Distributed system | +| Decomp/002 | Real-time Chat (Discord) | WebSocket, scalability | +| Decomp/003 | Task Queue (Celery) | Distributed processing | +| Decomp/004 | E-commerce Orders | Domain-driven design | +| Decomp/005 | File Storage + CDN | Storage, CDN | + +## Процесс сравнения + +### Шаг 1: Architect декомпозирует + +```bash +cd ai_architect +# Отправь Architect (Opus): "Считай PROMPT.md и выполни инструкции" +# Результат: decomposition/*.md + specs/*.md +``` + +### Шаг 2: Coder реализует + +```bash +cd ai_coder_1 +# Отправь Coder (Sonet): "Считай PROMPT.md и выполни инструкции" +# Результат: solutions/*.py + tests/*.py +``` + +### Шаг 3: Judge оценивает + +```bash +cd ai_judge +# Отправь Judge: "Считай PROMPT.md и выполни инструкции" +# Результат: evaluation_report.json + evaluation_report.md +``` + +## Критерии оценки + +### Architect (4 критерия по 0-10) + +| Критерий | Оценка | +|----------|--------| +| Component Decomposition | SRP, loose coupling | +| Interface Design | Чистые API | +| Completeness of Specs | Детали для реализации | +| Implementation Order | Логичная последовательность | + +### Coder (4 критерия по 0-10) + +| Критерий | Оценка | +|----------|--------| +| Specification Adherence | Следовал ли spec | +| Code Quality | PEP8, docstrings | +| Test Coverage | Тесты компонентов | +| Integration | Работает ли система | + +## Штрафы + +| Нарушение | Architect | Coder | +|-----------|-----------|-------| +| God component (>300 LOC) | -3 | -1 | +| Circular dependency | -5 | — | +| Missing spec | -2 | — | +| Не следовал spec | — | -5 | +| Нет тестов | — | -3 | + +## Sources + +- [TaskBench](https://openreview.net/forum?id=70xhiS0AQS) — Task decomposition benchmark +- [Amazon Science: Task Decomposition](https://www.amazon.science/blog/how-task-decomposition-and-smaller-llms-can-make-ai-more-affordable) +- [TDAG Framework](https://www.sciencedirect.com/science/article/abs/pii/S0893608025000796) — Dynamic task decomposition +- [Microservices Decomposition](https://learncsdesigns.medium.com/microservices-decomposition-design-patterns-a4adf84a027f) diff --git a/__pycache__/api_client.cpython-311.pyc b/__pycache__/api_client.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fd0b7ae5a06009f5f6bddb9a75c4b456fae0980c GIT binary patch literal 10880 zcmb_CX>1!;dNU-4w@ir=byD(JqAb(VVJSXh`AB3-cD$BlMN)#bf`lD&MiONn%FHm9 z7%K24=|asK8#M@EAqS#ujjYmS0se4N7rne~fH)`$3|#^t1~6ctShW5}!*=WXSHJJg z@RZceF7o*Jz5C63?>pZ2eKWtVs8N>tt3x}ZPPaB!-Q=S`?Njcn0AnQbJ!WF zny#WL10~S&JMs?}Twl->^%eZJFkNk+PE)+)J&LyqHD4H^4gPwYo3z=W%`Uhr+G$0PLu>_bes%_gs40siZM~G)d~}Wv=EC*0;z=l&LNz4G!zNRf*91FPLllY z9=f4;jS?t4(P;xuPaAmytj(zI7#crQ@`yy|2~HANVKFF>^{_KBk%ca7kSv20a2-I|G3?;#^p7u>=BqEEouUNj=2%JU!g^N-P|Y2vXk( zE_f-v&^Nv$&&8sF1u-@+1ZAmD79=@vdi31>-a~!dLMWg;ws&DkbijB5T#$KK58z7S zmo@b%`6%L6Nyk6%BpS|fixYw@h6HH@wlDAkPYyWIIl+Y_foCtz2~jq}EwZB4i{(V^ zq_Au6nCQd@*B~HEsKp$vlK@gxS7^lgvh`I#1%`(}%oUiL10MKGdfH^8@;|;EXq4e? zf*I)1%sT`N?}UGqV3~39JKkfat-MRH%@eM}NoNdv^?Rmi2VVodUC_(KyP@plYlSMl zPS_!so3I-R(C(Ts^B!og=Ih}p4e)OiYM{Pm#>zKAy}PW=%r`?_ZAD!R)YVngd7;iz zQP&D}^?V1v6Ve8reUF-MhB$UX5T%eL0}HZ}AW2ZKkD7{I0&=(*4_*@F@@KMpxKNBN0N7jaJ+cTK3zLMn zFnbY5KQ=SNl10zN!(nzlBm?IbmLrQxgzpY4E_So~2M%kShzj!Mn0QHNLA~>&EXISl zo5CjbhLB=ety4yfGodS>he zJ#+j8)p`-cLjdHH>Htm%=$xS1@z4Wg&#Ikt;e{}_q}s5PmbJ*Ch!Bg*L5ns$fw&@k z?n53{aE+1y=0lP$m(RE%1}K^Hy^|&=6?UCupk&Rr$tWfCP~_L7`D@Fj z*--$JAQzdHN*Z}<`K<%9=Vb}S+n`jq@pv0>l%0DY4w29UveF>jGh75nQp4&Xk@Z+& zk%0CHy|caDY}cGDFGz!ZD3N=GMJ}=s7J7rRNS8+4CG(Wf#2|Z)TMR|w5sfcd4oEz* zAWM~xE>aE|0lnXd!zCag=K;$BKk}7BiUc;uo{0jV15*(qBU~eFX0^%*3RGEKq&7at zEmZc^$#xLL1X&oXSFoX|zPyqxiFi{;>?>S2uHDYCz?s77vLOjZ5w0ve1+I7#9Ocf?Y->zXn2XmK18CC&g25(!r|CuxPKB=B_m--b1!=?F3Iq~ zU^vbTEXU5pBpL7J-ludQXbp@Ulew_S0!@wiT_TdJYSx~p+KW3-%^-Nfv7l-eCAb_H z#17~v`Vj0!(1qhHAo0j9sx)01qIx;mKE9R`D z=ISwp?N=Na@4CH8tB^W%;~XSfOuJ_??is~7lXZEnF6SuPHc69iFKzr(X?;nHY4=3N zJ)t-!?lrQXyFPYp7}Jg2na1uF)77eM%kC9Z#@d)|_Ce8=ZEA;P$K8guOhb3-kkW7@ z-Ebt+a0DuykIht5=lXQ2Hr;q2(|7+jCcShSIxn24D>8<01G-HO=@>8 z8TlnG9)un5P4CUv&Y~T%G?HHGhN#i#6k0EI&A472Q%YtP2Au5Ni5g|)y z0`Qn7thB;jcHnh=r-fOkPzmN17C;z@faX|4S6)yYzPhhlo94Ab_xrd%5y6|3ZnhNC8askOy3BqNRxO$kWK&1#K+9ZW) zM3E`qgmc7N&2UR}4GW+%!hs5GXeNJaveH~E9_HDL0=acVa4$@qf`hk*q)-%=9SsT~ ztI=8v#Z;#*rHPdzqJpBjCq||wE)1O*9SKZM4Nbi~IWp-tYDjqz+Ql;fB;0oa8C3!8 zkwg_-N;H&UqO>7^0}lhZLjBI+SrtB;&9n{t^;xC$g|uTR;}}9A+nB9wSltiOd37q| z=~f&VwJKNLN?aF&5djQFUNtRn@|%v8)Maxii>{Yq97bs23rN1o7eFHO^jpSPsB6Zbn`mJ0t(kZGF`(vB z^GHo3d;&D^3H6y_*=nO?v@i9rUQj3VHJI{7qQsh#R#at^W}fT|^5)Mf)Jb%PfHI6% zDhWwCX`L~IK%Kl!|B~KMy-OE&v207)=J5_EVVU7ArRAVu(Qt`eOQM;#ULt+O3sD12 zMPDgfalshXCn5pE4G);3%jmRu;Daq>yFaV`TX{$83c~OU%8-s7ix<*3c^|^ zsWPS7HeXPoVNC@Ex^#VzM@Iw+3pU^RvfMA zp!%s&%92c%4U5JL)Mc8cE`WMQgG9OdOa~?JF0N)C{Xithz4;uvYkZWrw(Lwgx553N zZhJP)N?I3VKPsKLOV3X3FRnT1EXVnL!AJ%E{*fu@0#MMh^KB=b=fA(B=P%QjDebgn zR3`Pn*CtKy{JJCqJZUOl;XAb7!@U4(RZv#WahC+mt)v^Fnu`XV982g!3I$8_CEaq? z?xR6%m{wr-oF19#X2;J@0upTxiH@c0%7MumgY7`7-blK|mSYc~}nmRtn{$%p}80ZF?1G%JGGhD%BpV-0$ zN~~BgGImeg~4O@Q8p!Px`8~%sx+IhgBMJ*_}Qnl|Nd?05$cA13EN~m7zC{z zOjHxwbDT{u#F6JWsZRaW!Kj;wsg^l#yT!yMqI0Mg@EJ?sFHh9q`j&{hj%Z^rjiVQA zb3_rSpb2B|z>G>u3F|3XqQFD5Ypm391{LkF%fe33(@p%h>?jA;a(+&GH>+uRgRH+r zWk68{U%d}DA?^nNI#lqDct{k)=dr2-tIX(R1oIa3){F63)uL}kTfT{G$uuv;q9R_p z;!hD=Amc=V!|L-`a~f+bpwvXcT`7)YiIKvBupkok>m2qWikeAY0{;l!QpCILuhNvX zajbX=!2|%+9)>*yG_BP^^4g{}4cnsI;i?h+c_t(Z?J=itEGR>#?zp?sZhyw@SDahKdtUZ?Z_gcXPukm;@%Ab8m2u^C*38*y_{l9I|@&MD-4r5?)ccD z_|B)y03hD1)zVwOZ=TU|>BjL)b|UsZPQtBAR(&1-vr>wWb5 z7roV%9=oa5eelFg=fN!NyY9^H?D+I8%sCWxSm_&1$v57D1Y*v{v;r~#JVLNKlB=c~ zz27(Z?=<)~I#YEwTG9>2G7ZOal-<*r?cBR&zt_^fK9%V_aHr*f(sCf{+w;Be@Ezab zn_X$&iHz^W+Q?mR`{!dHkL3*XuEVKQU?l81Ou)^_V*VEY&81=~+ug6Q&*hByo}}f0 z(b(FC)_hwI!DB1cvG;mUib=O0%(Nd=yj#Sq*Oxm~c9MV4A(GCy;}lS9OV6E_o(&;2 zb>r1^%TT5TY#oEghX{9m>{L1t;hpCp0>Vj35KeMMgtv99Io2Gxlk^|IqOEZI1L~eU zd9qcn|9$fK6is=&nYul{c}A%{2so{(FM@1q+p0ZV+f4ZVPHm4;+mrHrKQMe}VEEQc zw@vARbD4p2P?<$;?!V*hPj#iegBkDO>d4)?=4)dgBFdZkH+BR1n)(SyJzLEG!|<(| zzdil;r!z-Ki2;8SzukTG zjLq=R?L%!Z9%R0u+)((&bK)QrzID_<;oG($1`4-**mC=z{S0OMjxs|2J0p#G6Up1^ z&mLmF+j+uyc7XZUej4Eb167+GPrraiKHLXDvv|R}D{%#)%ZXTb2DI)#8#m;wA8;8N z6HZW9;65bY?OxRgr7>`|MPRZob=$viqmjE;=Ne@ zJM6Z3LkBnZE1p4!se@XoxCSeub@0dEkaPUylKmK=wC#3`3-L1SK=Ge&;}Qb20)Nz# zb`6h=j!cad&)Te2Y`Z)&xbDD%m8dS#k5=<9Tc7xI8&itsD8$q&TB^8?Rz~Ylvazu; zKRG&W-i80ezXGt?PcEJ=WtF0tEgdVZUoUat!8Cf<-thpYu{qz1+QtdQ8_Eq5_*w=Xk~;zvh;H?UrJy*0Dz0Lf=HEw1y9 zyEEK_!k`k}L7(Y!8T6cS^R6U5sikfJ`et^xKbU`i{?Ec!!-}kivfQi)z#sH{BctNNdLs3~}X2LN}7N5f=e4Qhr2VOIlh>2qx$$wxZqOVgmU5v%T znhAslPA(rmg%5tk4o5g=iTKSS_y1T_dymJ!QDY{VP_bgM`WfUhfsU(R4>te~L) zXr`Kw_O^*6m7sczX6*N>YjX@{VD&C{&O)+Qs_19ApMV|w1iZZ0O zYn%`!p;jl@%h23QUQCl0=NgftWlqd{)n5DpNPGQl1KntpI0!WMc^$jHj{v2P_L&%= z-g1h5YCWobS$ACg5c;9qllA}vEtjV6Q9G`XU$&Upt59VzOR>sUF-z@I%45lF`xR=7 zn58#{p4PVvG$3$m O_<+x|M?HPF!da8(OK zM;bG+XCiw^f*m_nGR{Pkf!KlA zK>R@5jITXV3%;DI8>l}}KhSWXf$>ARc?0tf%wyqju5qC0K-0kd1M{UoruIm)RTwq$ zLf|bNylpW82O3r7g}{LYY7}Ut-nU2iaVKT<(KhP=Q?GgIrjFTssX(ssLAF*P zSNk9rRUp^+AaAKauJu7Ku0SSzkV`6%?LNq*70BD1$Vt3im7CgjD4;I;p7d4?o^1U1 z=1k{!S`*$gc;1KgKIv}traO@GK`yUAcK9GyR3JB~HID|8D@Vp~4YBiKMcDt3`7u{T*$j_%S= z4E8^WtjnR{biV&EcyV5sJ(@P8mFM$=N6hjtW>PBGI?KrNv96)q@?iS-BbmIG&FFiM z_h&L{MrEn``HkZ=jDJDg%*%raJP?o|JM)qaAPK1kRr#IJTac@7G}t$+4IRn!=k*RMOy52G9^91L!ow(GAI~B+ ze4-q)548ozu?au@UxEB1{!Rw|DIBP8nQ2@z)4X72KK7Q`XsAAXDFAYX$jQC4wSjo! z$$k9qgV?;UuX}0Ti>Xs7LvHokFC+Va>vmIfLX~y-EnJoNRuk`SaVzN-AF+=lRT`@q zl}2lhvR8jBI2zQypSPM_WO;=0Wt&LDjfXYUqt%0i_y~)vy{Fm9r8%3gsKEk_G~< zoWxa+hTJ*1kG?Fa%5iB-!Y?>hqbhh!qJ`D_@oXjXhtv7Qv2-r0CP)rFn)v)9`x03_ zk?!x$4Cgay>S~Mg<;WaQ4-Drr^nRR`uGZ|>aaJm9ShaTe#Kxo^`;r+*>_|{(LsCy! zZ%b?}v4e9rCv|N;F6V5p90Z2QMk1T9)~9tnqvcuJElHi2TYAsN*bAi9BS|^7bNB>% zBhp&Av9BM}5HH}chQbU(9+qnn-S_lJHiuVSFNbqOK=U4m^IX?NvC?3&n3Aj#54!l{qdy4H#K<@o9U401B?VckNbWka#9 zvsBl4a_>yM@zh<0yv1nS0y=&d{$Gewknhv-mXa0b90ozKXvJ`dI7AfZjCTuO1;Ym2 z#X;tI+U#ukDL|b&z&xpmw~8UoeD1oK@8XPKCTFETkvjY>OS@ zMq7mI*A^2Y@u5*~MoSR66{J_Aw?w-Qq~i5z^?SXvF2L7P635%sQLNigs@ovmu5P2P z+mO5I)#<(vry$>_$rt&gMwV)pKe6Ftz476!ziajG8#84Gko$Mmbez^=aEXv{rhZKK3iOjJ;R`m%bTRSs=4vQK&5yv}0X#!}rz@#g)@YuBi&z!d3jsIYED+E$wLqQ8XRkW0DV z92g7a#WNegh?F}XJ)|1?bN98Sz+ikupfjM$&(<6dJ{foxy{{+HX9GGoCP7^n=NqfZ z$5BFa8}%r!P~N4{;4vt#qw;A<59RADBvf)yD!lPB-un>>%+5zRPg20#TsetSj)vVixsTBKs4=CLjQ=%bK{bB! zxuOca`CNU%&lQco)fP6|E#ctM;CgD}I#@fG(EAT(FxZkn`>1CUkEL@X8P?rP6&4(< zrgQdQZMtuecaEuB%#)v$$~DVzf=hN;$t!pcYtR%9Q$SNYMiL4=#B+?FYHll6EKWEQ&gY#gs z^I(hfU?V@^9pJ6JZ_W=oJ9TOfcn>(iyTB`%!jR>a%{sxnvitb8^krzcQhNl+HsPoL z4-6NfHymv^we+<@F}l1IT|OI-Lbpx!|3YarnvzAOy`;1oO8aaOTo%R1B?4U`V)Lqn ze)-E^R%6eG1GNc5?wr)$Jb{0I)HQkH5AS^QP6UnkvdKG*cqawr&Z68oEq9h!m~#Y# zMIy$Gk1qq3135<=A_eFCQJ3IVFnH#EDJOMLN(Vz^KY40Tqg93kvQdHJ-wyu`wsV3>1U)Go43Ygrl!JICr+Y;bAQ0wf5R`L(<#3Kc z`JJf*xH53L7SH^*=XD4FOx_mxk+d!18Vn%?fhmoDhnM1}(umr?c2j9I>%r4S_zhMX zsd0}Nw%CpPk@T^&-j9xLej6J_;!TC4Sx>ChGyNl4Hh&_SD$IAl(>aVYukB3sYFkiE z+U-QP5n)XuHF(+%BD;z75ZO!Q0g%e3i_gncX}atax?8c&BOA(I{~>yBRa&v6*@~?x zDr-y1T0>b&tyq#8Bu=OmOHwQ5;MuWu$ZW+bP&ZpK)~8hcTeB$tso~L;=-o4Ttf;d%(4i4qlr`Kb4tM_W$ z(WkmW*_*8BHVh8+S>e6j5m zWLzlJHPJbvM86(-DP+{IoBG`QVWayY?Bk)L@^DFc*iat+pyk%rfBTi+o;*@)=`6K$ z8jaq4Jp4i8)-&D4qK&jG8^@2~|Aht$@_ky_ShB*L!ypJ2tr!jwhlt{w@neEl!4M#v zPM~?d3W3H?ZN-J zUG51)&IcvXey3~`vT?~LCL7hzJK?t=vECL^>l)G#b|q>wE4>qQzq62%@f(nmwM_!NTYJZRLb^iB%B~e8RR-rQ#%N( zj}&ZVQjnFg4@-JbGVM!158N3?)d=wO?qUAm67g6AHm$5F82P z3Jwv6h~gZQg{J*Q1w(*vI)UPuf;xA^agFip>V=GJQ0IN3GA?GyxR{E+3K^goNe#T?esJv@CT(m*i6K za3-yy?_I7LI%-P3Scgb@1JaM{fI|AA%oroImPl&910hJuWc6=W6NKT=YDZ5ubxwcx z3&#G(jh-h+x;-S22!T-1ir@%wh$zk>sb{9GU73%%{1fY7_C z(qXFDGdB1U#t?tgRl3a%aR)^%O)J;4L#h4Qfea>>nVD{4t+gmV&$%$`SyWZ{>A9h2 z_hYqn!~~XQHJwju_e11x^)A#wkQ!d(Q` zs3+iNA`ihA#YzIK-v_50)iV7<=n!XAQ^AXNSSha~|B`VwJE9#z-D@EtD~Mcwio~Z! z+~$^<{i4*SdH+ku{hRpdZ&VYS;m~@AR=EC0i;X>x6}LWK+WI(2$R|q56Nd7Hke=(O z;_vP^w%ku~50sP#4CMh!FFaao*;s1XXf%3vlAfz3^TwiehO&-&yX!7AP>}D_%DR#j z<{Sn=uxQ0_h&V(P=a6b>Caz!z5KbphJX28Tj#v&BCE<8yDuE~6a6RdDoRDs~o^(S8 z&yMwkOx@5QYIcYNJ#E4BZF0}@$oW+gs7rd%`};h8m+!{SoXf0nUd(q?u3YR1d|?r- zES`iUuH0xA_#N5X!8&z|>wOk-%zxF@W~_Nchq?MWJPtN6DCqJ$gLQxv1B|}wDuJy; zllK~*K`-vtW;c@*%wdO*6CPUX%dDW)M4CE!%wG`o!Qib2-h#5Zltzp8e3T{vXvYz+ zogh%CgBZQZFrOj~Y3ad387>R%A<(@bD%D|LP>QxQGSjr=_0%h=$(CYMvec9`YOCz9K{3%R32acJ z?XW>{^6U)l5PMgupyJ^W&TSET{g9h=Xh&2FnXjKCxd)|pqt;&D6}-DS_~Yg!yS9gZ zyrGuD+vU3h(f0zxe=jIeSZ3j7`R>-pdy6H|exwwen7sTM8tlqf)VqAR!gmiA`(ueP z96iw@ei$p@#j(fNX&G>BU@SBm(tn_0%-pF0*&A z3WD32fQ|H6C;Q~*QPzA=9%aJ^CA$?rHEb@p4d)xIE5@Qw=XKeN&-DyAtR=SeKghX`g$ExpjEE_BY$Fgtk2`$8})Y@=TZ6}dkMD7O3o<aIyCNhB2$fJu!mcLprh;uc# zdja?c?P0|0)Ve`YWEVCXyoac3)IIzYO8d9aGKGm;eT&huzF3zk z)urIlFdUe-u+*@^kW-UAAZI9K;J9JMWY3uu#fDU=0salaN*Qq$;1nD=H7%z~a;nHE zVJr@Ma2Ah491H=%890hVCVQMmI5W$E$Km86L!?KT=VHcMMQ~yO@Y_FVSa9=#KihXW z-dKt+!@`(JnMgk^k-;&%4#<=J#dv#(FCem(5h0pee>>OLa1J>ib1m+1FhnwB%uzhe zr0hECcOGHslE@J05$3skOzZQ7c)6>0Ql>toPRh;h391~MZ_^x_L(}XT9l2i9{876m zH}BD}#XY)ahveox`n9-6*XxGd9E$n>EbCY|Bv!c99=+XccSCkPvd7cw;3KdvqmW#& zK8?`D|AQXD#eXL9OX>@}0v^U?Y3hotJn<;rT)U=`uIua8D2t_A|2`7@2tWNzU)}nH z&%7D}pUR(cMeF7jes+~*nzVi%zsoUnXypu?7z_7K{A2vziL)o`J>&Hl{}1~hJ)^)LXPPv9$+kI{(BtL9w}c)XN*M7e zq36!{pggL#56Uxt;Dhpvu)!s0ge^E#@-0?V0ZKH}?>31KQqjPL#0<#k# z{K8`q_mf8RNbcIEF}$%5d$weJ;lTZDg-65s|AMR1U;ig7c7xBpXQs;c$@1XvWW`+f z%6>~e#V1RRzY%87Omq&Q7+Rw~bn5j~=1&1Sf%OH>~_Rte9bqbFQzJeoh%M}{Y zEqucgg{5O6tS z+B+sAj!Uj*?7=pcG|sXbjKfafpKIuB8FXJp(}Ttx9~%%s-E@Fa-3_HOB}nNtoaP*iqq zeuUDB9FPEEp3IE33h%@K;J5RSI-sj4HhK-2W_Uj|!>?4a_Hehn!1AgH=hDrdi9z1282Gy`WtC9PToW1*;o$jRwDlOS8?f#$=b9dQV#ieHFR~ z>8hr?5a_7-|E}Ib;~Pv7lv5#eg}acbt8EpUs=Lh4Xx&cbMH}pIhURfYFAQt_Q=p}X z%l0{z$L(HTl*c>#3oXN`v5Qi8aZJmoj`V7#)lnYJ6#9eAbxxI>oG7Ln`sf_o&|goR z2%DN`1e!$s3+T!8cs?317Q@E~8@?xv#YbbKar5~g3#Oc_E=1n|&qoN)$2>xNpAT0G zyY^yk9mfY1ccausbB$W9+N91Otu^aJnM0jiPb;T7p>=AZu{aqeeq^)6<^o^1!ORlv zRcWw2gbNnTrsE@a2^jjq4XZ|p2PPQ>04uW7FKghX0f1+zTCK-e{bwg1T5SykfnYb$S+R@jCnix ze(u)Ox4ho=O50@Zna0W5$=YJ$`cmV15zRz5H_S%y*tgZ-(S~by2$&ikoWC=B0;sM~ z&n(wBFe)eqbD6<%g!{kIlQLJ??nD`w7aV3YT3>$;tWFJ~O|tL>vWGNo|FZPx3+`68*T*2Y!WrpiZA`*T1``04MVl71=7Bx0r~ zp;%}KH?4i<<k$t1|8ck4^PVu4OlqF^W?#t+M8=(nFj~07TTxq3{bB&I6MPT%V=({+-zOiqtm)|4~&IIFtYh^TmV9Ng=pzFUdRX+)uMO#R#6KDB>-;3EK{Y#xOE6c2Ev~x049@e1237Ke zLipZ7q=R#?ysRdxTg@yq5h?*W;lt=zSuso1DMB03^onsKSJR7Tnb|u!*O`@-J~M|o zx3&>SYy0nUQQChXvJS-AfOctr22Q23D&BsY=Y*3gaz*%;K>jyE|95nuE1J)EXr*Hz zTKl>EQ=881qjhGxO3E%n*(KJX-F8l$>N)omMcrLe?lzRWKd5j0`ru206HgTDSC{Hn z8%mXZX8zLB{MF-%g?+MEzot~b#!#y47M5%tTPJQOD@VoLrhZQRs>| zv?Hp8SQ}%dtOnpq+V)6$mIeQ6nY?F3Zwfq**(~9u#ox`UXBNjbHo{z{X0b+uR_vHPT<$Q{DHlnPX4`cf zriy+oWGVH`*ye6)Kb1wlF_+w>wx4a@l^qyMsO~WJ#w9rQo8iA|R5~K+fL1&mp>7D< zFuN7O`X^;n(f_rI_TvWIG0)tNZ#(9}p&e`RsVmR8m=DVHEUEL%Pnx#($tM1#b6(AC;K00P zedaCG&I9>R_~|bOtEfIPmuIHrxt^(&=eCo6v$Le^G?bkm&R=3I?JCaSRGJUZlyWq6 zZ88;}S$ykvw|#rtT#5VYs_@w5bdXiyeyf7PeQd$e z*Z6Zhq3Ld`VU;rQ&(OmYiUyiZ4k z_4S~D3BO7wtj;D2p68)1+n#Z*@g)Ixy;fsTpgmrgq3YHO1=(NK6_a&PTWKDGZJ2D5 zF_}|e)s10;YobP|%2iZdXWq7A>Y09k`sT!mu-D9usc$0IWf12Xuz+G_sk)77lVh-g zeASzq>zqPuy{>Z&GI^Q@jv0V zGshxKzr%MNOdR)A9{D^6YdT;Kw?yUG@CdmMr>{9^DrJ!&LLSR~J|)4k-B^yOnOp{^ zzxX~S7^Vc)IX9N;c%+$evX;9z3F2JkFppx(Vdtu#VG(SW&cbxEpHk={A~Xc$(8;I< zs;qhCpM;>xL`C0|enlzR>3 zUK)y0UQ*!ucPcopi1GUm8*ecdcNQBrmKrz0>5-{}9hnNh8->fHiEYKj50n-^U@Y+N z}3+^3aP$qI8OgCJP6VmL$`B8qdy3xZd{5FngRpm?UB z&KBi-Ev2?C zMyq!puba8G{Y;OM=rokh@iF|r&_F@HPb-}zE6h0zf?&~#;Sh0%D9#xl6TAwB0O523 z#WMwU?ug}JQ4)@KrV{wsMR=BG0~WbNp)2Chj;I!5+KZL48i0?j-Lw4OK=A#5e6JjN zKO%uvS4`I7LH~3VlWUEwT|?FIjO9D$S@;KtZjPowNST{cojWr3k)Rv<{LnUgP9zWa zS2nU~ja{Y2uJQ0p%hJ~iuM{TN6kFO$E$v35cmK?|REE=0bi*t{PDjy;vkvWu zY9S^EuLb3DaQAIJ(ct;0+*21hKTiT>p15JqGDf$a`Cpr$(6@+u8>HWUE99=GB zHILsM#HjR6jaM!7M+=|yD2?sq>l&XXx|ZAw^4u_D9vqb&c6R=sZ6iCoD4{D<{2Tpj zo2MfM6<>5M(BTqYJ+I;p72of(ZJv>JF$)o97LDO7tj^&6+_mb*bxymp;OSPlJ54l? z%q;gl-du8h!SNm6bS{_Bhco@zgYbWo;NKF0m{c)(OU`jD$2dL)d(6!{SMCdVV8tgi z82>tAlYK%13N-ao*_*(Hp|2dI7r+|INJ$c zF+2s?s=r1bU~_3bV(zqJaA;BWIl#O~5%8=HgeABbrg6$5{}hl)(ducurT0O32CCGU zIo}s_T9>=h+S1A+N!_&tX+@t;lb|z`)o5+Op|w4o?ms$o@L&R+-}DJ6ZS;XNnmD2_ zizhPa{=-ZFok*nf7+V<5bN^h2zWpuQ{@q=N`0Zc06NVgV)wa1KK$xhYifUzW#KsetF!W=rA&h?qs-Y2e_XI9Oecst3lHOQ09iRIaluyNopimo;bf)>t5Lrh`;H7sl=OqOKcuIiSa(OM?hbfFQvwa$qLR)WM6g)DxrEx3 zH-EK@j^dk3aXKEpIN#n~RK6l*RdKm*8=TgCRhaDND&A$X6r+24RjgW3AIT zF#tGsc3)kOv1ld6QBjp`gj@Pv-{RBTnqY`DM1NilSq=FPoFXO}F5Jd?qpYh*9nqnK z5MDaocUz#b4|hL3q@M6I&|{z0)_#KPDwA3LGZc_1K`)LXIO2;HYHY(dr^$V}l|N&2 z8XDnb=kBBA+CL!eZhEG^i$F!MuqL!ia;ZaIQ;#?%cV|Ncm<`zU5({5(aGbGzVWtt- znfSr{v?9?y4cDzY7WiK9<9k!#haVEo}iC7QwZI}KLzV0RZZh9ef6BN>L2&g z*16D^3bNi)*tPb_c?Mc1!M5v8Y>}T(nfzDKU&VV4@1Z{K*bxK$g@5##*}d4`bH=;Q zZEsn(DK~WJ5V;ej$FA2q)WpV=ToO$*%xi%c&2rrsR^8yK;1>mY%xaSBRS6}jDMudV zU*1OBT#gLDt_8+75EP`0(3h|=+NC<>gH}dFp`8f{Dj}p4dD%2C!l8Ir?eLQ%F_K8c zC5F+o5Bs_9(_1IQZ`K?0vAlyA&Yf!>|CtI9Ob?!5jcc;L95GKEK9;{NJ~g2IPo#N}Nl6fX z&FIb93%z4Mmzyuh&8HuK^{Jw~yd*C-Ff*rHzbb*ZX*}epRX7 z_4P0N%U@mu&;Y}!{s4J-S;s?$-!zET4n8Jr@Z?3-5hm6Ux&Mk&hT z(0Uk(sm2gI%9NpaF349T0tR7@G-IvPI57b5ojyGAAX*8VlJolqCGvjn<~uQ!Vb)4q zKM5OC`?tF{^sEb>Unlo$h@9_|K$Dn%?CVp9`uqCI%F`p+Ts}Lfv!|)NsBicL-T4&P z5n(}}(lXC#m^Um(1&ba-#^Y)qTMAaAWy*CUgIRP!ka}RK|ENZ9tVV)fyNAdm5mNXx zQcn0o&BisDQb`@9a^zt4cz#67Xq|-UBC?stBSbz=rWUnqA;U&Sn3Bn~0`}0e zt_^>8n~~d9W&6O8I+DxWsr_FZ;$;Zve}hZLrxGM-Rt`$?Y=B5CAW0_!K7aKm+22ec zdXoLk1lo;i`v-x#lk9IMu*s;l&jeN(?)`(nR-@XEm$gQDp>4J%CgH;oAeVxHnt2wZ zEhybiLFR=de4$DZ?;(|9aY<^Pt%*qZ8U+Xy zWP#u`+km(PdpQsrK%6BuAVy~bu>r)n#Re!6#;rkY0C5)DfGFhvVgrcNY6BDrUwi?v z0mO0Sph);81&9;S?gYf?6d*Q$IF74`5CFsm5XVsuinN(dvDpR?$5Dn_3CqktYyffE z?5n7gutosH1`sD<18S+FKx_bU968j}JqED>#940V5TzVIYyffiW&T`hy&$ztv>Ge6 z^SvnTC`mhJq=@+_cyAnXJq=?Kw^3usn^73Fa4H2pCIBpZQh{!`@tToV87|(Mn*^>3F0+n84 zOfelMN9|reEk%n%6c7dengaao)@hUal+XbczTd&nQhg{#4AL-+k~G4Mw--dOo!ggA zRa88Wx}J0#^1DRUUDOs7>bMNXspv*+A!Dy>yy^;Mk1tGUa( z8g%)Y8C?~HtPF6-^D+w-DjwiQJ+5`l0V>xl9^$)L=OAW(>3>cE)ND4dX;6AmKok%K z<_hrr;G;1H7ITC8>OiNT0KgjD+A!8N9O$zH7+A~=!UIz#6=+hGePSq+4!>{X0*kpp zlTJ$SjCJhJ%DzyP-W`5lhm#5nN-qkC0z+!F?9+>2000 chars): TEXT type supports unlimited length +- Unicode URLs: store as-is, encode/decode at application layer +- Expired URLs: soft delete (mark expired) + async cleanup job + +**Alternatives considered**: +- NoSQL (MongoDB): rejected due to weaker consistency guarantees +- Separate deduplication table: rejected, checksum column sufficient diff --git a/ai_coder_1/subtasks/Decomp-001-02.md b/ai_coder_1/subtasks/Decomp-001-02.md new file mode 100644 index 0000000..4971ea3 --- /dev/null +++ b/ai_coder_1/subtasks/Decomp-001-02.md @@ -0,0 +1,80 @@ +# Subtask: Base62 Encoding/Decoding + +**Parent Task**: Decomp/001 +**Subtask ID**: Decomp/001-02 +**Dependencies**: None + +## Description + +Implement Base62 encoding/decoding utility for converting numeric IDs to short codes and vice versa. This is a standalone utility with no external dependencies. + +## Requirements + +- Convert integer ID → Base62 string (0-9, a-z, A-Z) +- Convert Base62 string → integer ID +- Support IDs up to 10M (fits within 6 characters) +- No external libraries for core logic +- Deterministic output (same input → same output) + +## Technical Specifications + +**Algorithm**: Base62 encoding with custom alphabet + +```python +ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" +BASE = 62 + +def encode(num: int) -> str: + """Convert integer to Base62 string.""" + if num == 0: + return ALPHABET[0] + result = [] + while num > 0: + num, remainder = divmod(num, BASE) + result.append(ALPHABET[remainder]) + return ''.join(reversed(result)) + +def decode(short_code: str) -> int: + """Convert Base62 string to integer.""" + num = 0 + for char in short_code: + num = num * BASE + ALPHABET.index(char) + return num +``` + +**Data structures**: +- String lookup for alphabet (O(1) char → value mapping) +- Precomputed dictionary for reverse lookup optimization + +**API signatures**: +```python +def encode_id(id: int) -> str: ... +def decode_id(short_code: str) -> int: ... +``` + +**Error handling**: +- `ValueError` for negative IDs +- `ValueError` for invalid characters in short_code + +## Acceptance Criteria + +- [ ] `encode_id(0)` returns `"0"` +- [ ] `encode_id(12345)` returns deterministic 4-char string +- [ ] `decode_id(encode_id(n)) == n` for 0 ≤ n ≤ 10M +- [ ] 10M IDs encode to ≤6 characters (62^6 ≈ 56B > 10M) +- [ ] Invalid characters raise `ValueError` +- [ ] 100% test coverage for encode/decode roundtrip + +## Notes + +**Trade-offs**: +- Alphabet order (0-9, a-z, A-Z): optimized for URL readability +- No leading zero removal: preserves exact ID mapping + +**Edge cases**: +- ID = 0: return "0" (single character) +- Very large IDs: test up to 62^8 for future-proofing + +**Alternatives considered**: +- Base58 (Bitcoin-style): rejected, Base62 gives shorter codes for same ID +- Base64: rejected, includes special chars (+/) not URL-friendly diff --git a/ai_coder_1/subtasks/Decomp-001-03.md b/ai_coder_1/subtasks/Decomp-001-03.md new file mode 100644 index 0000000..6268811 --- /dev/null +++ b/ai_coder_1/subtasks/Decomp-001-03.md @@ -0,0 +1,91 @@ +# Subtask: Unique Short Code Generation with Collision Handling + +**Parent Task**: Decomp/001 +**Subtask ID**: Decomp/001-03 +**Dependencies**: Decomp/001-01 (Database Schema), Decomp/001-02 (Base62) + +## Description + +Generate unique short codes for URLs, handling duplicate URLs and hash collisions. Implements idempotent URL shortening (same URL → same short code when possible). + +## Requirements + +- Generate short code from auto-increment ID using Base62 +- Detect duplicate URLs (return existing short code) +- Handle hash collisions gracefully (multiple codes for same checksum) +- Support custom user-defined aliases +- Ensure uniqueness at database level (UNIQUE constraint) + +## Technical Specifications + +**Algorithm**: Counter-based + duplicate detection + +```python +def create_short_url(original_url: str, custom_alias: str = None) -> str: + """ + Create a short URL. Returns existing short code if URL already shortened. + """ + if custom_alias: + # Validate custom alias format + if not valid_alias(custom_alias): + raise ValueError("Invalid custom alias") + # Check for conflicts + if exists_short_code(custom_alias): + raise ValueError("Alias already taken") + short_code = custom_alias + else: + # Check for duplicate URL + checksum = sha256(original_url) + existing = find_by_checksum(checksum) + if existing and not existing.expires_at < now(): + return existing.short_code # Return existing + + # Generate new code from auto-increment ID + url_id = insert_url(original_url, checksum) + short_code = encode_id(url_id) + + return short_code +``` + +**Collision handling strategy**: +- Primary: database UNIQUE constraint on short_code +- Secondary: checksum collision → append random suffix +- Fallback: retry with new ID (incremental) + +**API signatures**: +```python +def create_short_url(original_url: str, custom_alias: Optional[str] = None, + ttl: Optional[int] = None) -> str +def resolve_short_code(short_code: str) -> Optional[str] +def check_duplicate(original_url: str) -> Optional[str] +``` + +**Error handling**: +- `ValueError`: invalid custom alias format +- `ConflictError`: custom alias already exists +- `DatabaseError`: constraint violation (should not happen with proper logic) + +## Acceptance Criteria + +- [ ] Same URL → same short code (idempotent) +- [ ] Custom aliases override auto-generated codes +- [ ] Collisions handled without data loss +- [ ] Expired duplicate URLs generate new codes +- [ ] Custom alias validation: 3-8 chars, alphanumeric + hyphen +- [ ] Database constraint violations never cause silent failures + +## Notes + +**Trade-offs**: +- Duplicate detection on checksum: fast but theoretically possible collisions +- SHA-256 chosen over MD5: collision resistance (astronomically improbable) +- Custom alias override: user choice trumps deduplication + +**Edge cases**: +- Same URL with different TTL: return existing, update TTL +- Collision after 10M URLs (Base62 wrap): increment ID length +- Custom alias matching auto-generated format: allow but warn + +**Alternatives considered**: +- True hash-based codes: rejected, not sortable, collision-prone +- UUID prefix: rejected, longer codes, no ordering diff --git a/ai_coder_1/subtasks/Decomp-001-04.md b/ai_coder_1/subtasks/Decomp-001-04.md new file mode 100644 index 0000000..3b2b1b3 --- /dev/null +++ b/ai_coder_1/subtasks/Decomp-001-04.md @@ -0,0 +1,90 @@ +# Subtask: HTTP Redirect Endpoint + +**Parent Task**: Decomp/001 +**Subtask ID**: Decomp/001-04 +**Dependencies**: Decomp/001-01 (Database Schema), Decomp/001-03 (Short Code Generation) + +## Description + +Implement HTTP redirect endpoint that resolves short codes to original URLs. Must support both 301 (permanent) and 302 (temporary) redirects with <50ms p95 latency. + +## Requirements + +- Resolve short code to original URL +- Return HTTP 301 for permanent redirects (default) +- Return HTTP 302 for temporary redirects (configurable) +- Handle expired URLs (404 or custom error page) +- Support query parameter forwarding +- Log all redirect attempts for analytics + +## Technical Specifications + +**API endpoint**: `GET /{short_code}` + +**Response flow**: +```python +def handle_redirect(short_code: str, temporary: bool = False) -> Response: + # 1. Lookup URL in database + url_record = db.query( + "SELECT original_url, expires_at FROM urls WHERE short_code = %s", + short_code + ) + + # 2. Handle not found + if not url_record: + return Response("URL not found", status=404) + + # 3. Check expiration + if url_record.expires_at and url_record.expires_at < now(): + return Response("URL expired", status=404) + + # 4. Log for analytics (async, non-blocking) + async_log_click(short_code, request) + + # 5. Redirect + status = 302 if temporary else 301 + return Response(status=status, headers={"Location": url_record.original_url}) +``` + +**Caching strategy**: +- Redis LRU cache with 1-hour TTL +- Cache key: `redirect:{short_code}` +- Cache miss → DB lookup → cache populate +- Cache hit: <5ms response time + +**Performance requirements**: +- p50 latency: <10ms +- p95 latency: <50ms +- p99 latency: <100ms + +**Error handling**: +- 404: short code not found or expired +- 429: rate limit exceeded (client-side) +- 500: database errors (with monitoring alert) + +## Acceptance Criteria + +- [ ] Valid short code returns 301/302 to original URL +- [ ] Invalid short code returns 404 +- [ ] Expired URL returns 404 +- [ ] p95 latency <50ms under 100K req/sec load +- [ ] Cache hit rate >95% for popular URLs +- [ ] Analytics logging doesn't block redirect response +- [ ] Query parameters preserved in redirect (optional) + +## Notes + +**Trade-offs**: +- 301 vs 302: 301 for SEO (permanent), 302 for tracking flexibility +- Async logging: eventual consistency acceptable for analytics +- Redis cache: added complexity but 10x latency improvement + +**Edge cases**: +- Redirect loop: detect and break (max 5 hops) +- Very long original URLs: no truncation, preserve as-is +- Concurrent redirects: handle race conditions in cache population + +**Alternatives considered**: +- Synchronous logging: rejected, blocks redirect response +- Edge redirects (CDN): rejected, adds external dependency +- 308 redirect: rejected, less browser support than 301 diff --git a/ai_coder_1/subtasks/Decomp-001-05.md b/ai_coder_1/subtasks/Decomp-001-05.md new file mode 100644 index 0000000..1e01b71 --- /dev/null +++ b/ai_coder_1/subtasks/Decomp-001-05.md @@ -0,0 +1,119 @@ +# Subtask: URL Shortening API Endpoint + +**Parent Task**: Decomp/001 +**Subtask ID**: Decomp/001-05 +**Dependencies**: Decomp/001-03 (Short Code Generation) + +## Description + +Implement REST API endpoint for creating short URLs. Supports both auto-generated and custom short codes, with optional TTL configuration. + +## Requirements + +- Accept POST requests with original URL +- Return short code in JSON response +- Support custom alias parameter +- Support TTL (time-to-live) parameter +- Validate URL format +- Rate limit to prevent abuse + +## Technical Specifications + +**API endpoint**: `POST /api/shorten` + +**Request format**: +```json +{ + "url": "https://example.com/very/long/path", + "custom_alias": "mylink", // optional + "ttl": 86400 // optional, seconds +} +``` + +**Response format**: +```json +{ + "short_code": "abc123", + "short_url": "https://shrt.io/abc123", + "original_url": "https://example.com/very/long/path", + "created_at": "2025-02-04T12:00:00Z", + "expires_at": "2025-02-05T12:00:00Z" +} +``` + +**Validation rules**: +- `url`: required, valid HTTP/HTTPS URL, max 2048 chars +- `custom_alias`: optional, 3-8 chars, alphanumeric + hyphen, no reserved words +- `ttl`: optional, 0-31536000 seconds (max 1 year), 0 = no expiration + +**Error responses**: +```json +// 400 Bad Request +{ "error": "invalid_url", "message": "URL must start with http:// or https://" } + +// 409 Conflict +{ "error": "alias_exists", "message": "Custom alias 'mylink' is already taken" } + +// 429 Too Many Requests +{ "error": "rate_limit", "message": "Rate limit exceeded: 100 req/min" } +``` + +**Rate limiting**: +- Token bucket algorithm: 100 requests/minute per IP +- Redis-backed for distributed rate limiting +- Sliding window for accurate throttling + +**API signatures**: +```python +def create_shortened_url(request: Request) -> Response: + url = request.json.get("url") + custom_alias = request.json.get("custom_alias") + ttl = request.json.get("ttl") + + # Validate + validation_errors = validate_request(url, custom_alias, ttl) + if validation_errors: + return Response(validation_errors, status=400) + + # Check rate limit + if not rate_limit_check(request.remote_addr): + return Response({"error": "rate_limit"}, status=429) + + # Create short URL + short_code = create_short_url(url, custom_alias, ttl) + + return Response({ + "short_code": short_code, + "short_url": f"{BASE_URL}/{short_code}", + "original_url": url, + ... + }) +``` + +## Acceptance Criteria + +- [ ] Valid URL returns 201 with short code +- [ ] Invalid URL format returns 400 +- [ ] Duplicate URL returns existing short code (idempotent) +- [ ] Custom alias conflict returns 409 +- [ ] TTL sets correct expiration timestamp +- [ ] Rate limit enforced at 100 req/min per IP +- [ ] Response includes all required fields + +## Notes + +**Trade-offs**: +- Rate limiting per IP: simple but can be bypassed with proxies +- Duplicate URL returns same code: saves space but reduces analytics granularity +- TTL in seconds: more flexible than presets + +**Edge cases**: +- URL with fragments (#): preserve in stored URL +- URL with query params: preserve exactly as provided +- Internationalized domains (IDN): store as Punycode +- TTL = 0: means no expiration (NULL in DB) + +**Alternatives considered**: +- Rate limiting per API key: rejected, adds auth requirement +- Hash-based codes: rejected, less predictable, collision risk +- TTL presets (1h/1d/1w): rejected, less flexible diff --git a/ai_coder_1/subtasks/Decomp-001-06.md b/ai_coder_1/subtasks/Decomp-001-06.md new file mode 100644 index 0000000..f578c7f --- /dev/null +++ b/ai_coder_1/subtasks/Decomp-001-06.md @@ -0,0 +1,91 @@ +# Subtask: Caching Layer with Redis + +**Parent Task**: Decomp/001 +**Subtask ID**: Decomp/001-06 +**Dependencies**: Decomp/001-01 (Database Schema), Decomp/001-04 (Redirect Endpoint) + +## Description + +Implement Redis-based caching layer to reduce database load and improve redirect latency. Uses LRU eviction with configurable TTL. + +## Requirements + +- Cache redirect lookups (short_code → original_url) +- LRU eviction when memory limit reached +- 1-hour TTL for cache entries +- Automatic cache invalidation on URL updates +- Fallback to database on cache miss +- Handle Redis failures gracefully + +## Technical Specifications + +**Cache schema**: +``` +Key: redirect:{short_code} +Value: {"url": "https://...", "expires_at": "2025-..."} +TTL: 3600 seconds (1 hour) + +Key: redirect:exists:{short_code} +Value: "1" (for negative caching) +TTL: 60 seconds (1 minute) +``` + +**Cache operations**: +```python +def get_cached_url(short_code: str) -> Optional[dict]: + """Get URL from cache, fallback to DB.""" + cached = redis.get(f"redirect:{short_code}") + if cached: + return json.loads(cached) + return None + +def set_cached_url(short_code: str, url_data: dict, ttl: int = 3600): + """Store URL in cache.""" + redis.setex(f"redirect:{short_code}", ttl, json.dumps(url_data)) + +def invalidate_url(short_code: str): + """Remove URL from cache (on update/delete).""" + redis.delete(f"redirect:{short_code}") +``` + +**LRU configuration**: +- Max memory: 1GB (configurable) +- Eviction policy: `allkeys-lru` +- Expected cache size: ~2M entries (500 bytes/entry) + +**Failure handling**: +- Redis unavailable: degrade to database lookup +- Connection timeout: 100ms, then fallback +- Retry strategy: exponential backoff, max 3 retries + +**Performance targets**: +- Cache hit: <5ms latency +- Cache miss: <50ms latency (DB lookup + cache populate) +- Hit rate: >95% for popular URLs (Zipf distribution) + +## Acceptance Criteria + +- [ ] Cache hit returns in <5ms +- [ ] Cache miss populates cache for next lookup +- [ ] Expired URLs not cached (or cached with negative result) +- [ ] Redis failure doesn't break redirects (fallback to DB) +- [ ] LRU eviction respects memory limit +- [ ] Cache invalidation works on URL updates +- [ ] Negative caching prevents DB hammering for invalid codes + +## Notes + +**Trade-offs**: +- 1-hour TTL: balances freshness vs cache hit rate +- Negative caching: prevents DB spam for invalid codes +- LRU over LFU: simpler, good enough for temporal locality + +**Edge cases**: +- URL updated while cached: eventual consistency (1-hour window) +- Redis restart: cache warm-up required (can pre-load top URLs) +- Memory pressure: LRU eviction may drop popular but recently unused URLs + +**Alternatives considered**: +- Write-through cache: rejected, slower writes +- Write-behind cache: rejected, risk of data loss +- No caching: rejected, cannot meet <50ms p95 latency at scale diff --git a/ai_coder_1/subtasks/Decomp-001-07.md b/ai_coder_1/subtasks/Decomp-001-07.md new file mode 100644 index 0000000..4e47a89 --- /dev/null +++ b/ai_coder_1/subtasks/Decomp-001-07.md @@ -0,0 +1,110 @@ +# Subtask: QR Code Generation + +**Parent Task**: Decomp/001 +**Subtask ID**: Decomp/001-07 +**Dependencies**: Decomp/001-03 (Unique Short Code Generation), Decomp/001-04 (Redirect Endpoint) + +## Description + +Generate QR codes for shortened URLs. The QR code should encode the full short URL and be returned as an image file (PNG format). Supports both on-demand generation and pre-generation. + +## Requirements + +- Generate QR code from short URL (e.g., `https://sh.rt/abc123`) +- Return QR code as PNG image +- Configurable size (default: 300x300px) +- Configurable error correction level (L/M/Q/H) +- Support QR code caching (store generated images) +- Serve QR codes via dedicated endpoint (`/qr/{short_code}`) +- Optional: SVG format for scalability + +## Technical Specifications + +**QR Code library**: Use `qrcode` Python package (no external API calls) + +**API endpoint**: +``` +GET /qr/{short_code} +GET /qr/{short_code}?size=400&format=png&ecc=M +``` + +**QR code generation**: +```python +import qrcode +from io import BytesIO + +def generate_qr_code(url: str, size: int = 300, ecc: str = 'M') -> bytes: + """ + Generate QR code PNG for given URL. + + Args: + url: Full short URL to encode + size: Image size in pixels (width=height) + ecc: Error correction level (L=7%, M=15%, Q=25%, H=30%) + + Returns: + PNG image bytes + """ + qr = qrcode.QRCode( + version=None, # Auto-detect + error_correction=getattr(qrcode.constants, f'ERROR_CORRECT_{ecc}'), + box_size=max(10, size // 25), # Scale based on requested size + border=4, + ) + qr.add_data(url) + qr.make(fit=True) + + img = qr.make_image(fill_color="black", back_color="white") + + # Resize to exact dimensions + img = img.resize((size, size), resample=0) # Nearest neighbor + + buffer = BytesIO() + img.save(buffer, format='PNG') + return buffer.getvalue() +``` + +**Storage strategy**: +- Generate QR codes on-demand (no pre-generation) +- Cache generated QR codes in filesystem or S3 +- Cache key: `qr/{short_code}_{size}_{ecc}.png` +- TTL: Same as URL TTL (infinite if no expiration) + +**Response headers**: +``` +Content-Type: image/png +Content-Disposition: inline; filename="qr_{short_code}.png" +Cache-Control: public, max-age=86400 # 24 hours +``` + +## Acceptance Criteria + +- [ ] QR code scans to correct short URL +- [ ] QR code is readable at 300x300px size +- [ ] Different error correction levels work correctly +- [ ] QR code endpoint returns valid PNG +- [ ] Non-existent short_code returns 404 +- [ ] QR code caching reduces generation time on subsequent requests +- [ ] QR code works with damaged/missing corner (error correction) + +## Notes + +**Trade-offs**: +- On-demand vs pre-generation: On-demand chosen for simplicity +- PNG vs SVG: PNG default (better compatibility), SVG optional +- Error correction M (15%): balanced between size and robustness + +**Edge cases**: +- Very long URLs: QR code auto-version selection handles this +- High ECC requests: larger QR code size +- Concurrent QR generation: cache stampede possible (use lock if needed) + +**Performance targets**: +- Generation: <100ms (without cache) +- Cached retrieval: <10ms +- Image size: ~2-5KB for 300x300px PNG + +**Alternatives considered**: +- External API (Google Charts API): rejected, adds dependency and latency +- Pre-generation for all URLs: rejected, wasted storage for unused QR codes +- SVG only: rejected, PNG has better mobile browser support diff --git a/ai_coder_1/subtasks/Decomp-001-08.md b/ai_coder_1/subtasks/Decomp-001-08.md new file mode 100644 index 0000000..844ef39 --- /dev/null +++ b/ai_coder_1/subtasks/Decomp-001-08.md @@ -0,0 +1,144 @@ +# Subtask: Link Expiration with TTL + +**Parent Task**: Decomp/001 +**Subtask ID**: Decomp/001-08 +**Dependencies**: Decomp/001-01 (Database Schema), Decomp/001-04 (Redirect Endpoint) + +## Description + +Implement time-to-live (TTL) functionality for shortened URLs. URLs can have an optional expiration time after which redirects return 410 Gone. Supports both absolute expiration timestamp and relative TTL. + +## Requirements + +- Optional expiration timestamp on URL creation +- Support relative TTL (e.g., "expire in 24 hours") +- Check expiration on every redirect +- Return 410 Gone for expired URLs +- API to extend URL expiration +- Admin option to create permanent URLs (no expiration) +- Background cleanup of expired URLs (optional) + +## Technical Specifications + +**Database schema update**: +```sql +ALTER TABLE urls ADD COLUMN expires_at TIMESTAMP NULL; +ALTER TABLE urls ADD COLUMN is_permanent BOOLEAN DEFAULT FALSE; + +CREATE INDEX idx_urls_expires_at ON urls(expires_at) WHERE expires_at IS NOT NULL; +``` + +**API updates**: +```python +# URL Creation +POST /api/shorten +{ + "url": "https://example.com", + "custom_alias": "mylink", # optional + "ttl_seconds": 86400, # optional: 24 hours + "expires_at": "2025-02-05T12:00:00Z", # optional: absolute time + "permanent": false # optional: never expire +} +``` + +**Expiration logic**: +```python +from datetime import datetime, timezone + +def set_expiration(url_data: dict) -> datetime: + """ + Calculate expiration timestamp from various input formats. + Priority: permanent > expires_at > ttl_seconds > default + + Returns: + UTC datetime or None (permanent) + """ + if url_data.get('permanent'): + return None + + if url_data.get('expires_at'): + return datetime.fromisoformat(url_data['expires_at']) + + if url_data.get('ttl_seconds'): + return datetime.now(timezone.utc) + timedelta(seconds=url_data['ttl_seconds']) + + # Default: no expiration (or configurable default TTL) + return None + +def is_url_expired(url_row: dict) -> bool: + """ + Check if URL has expired. + + Returns: + True if expired, False if valid or permanent + """ + if url_row.get('is_permanent') or url_row.get('expires_at') is None: + return False + + return datetime.now(timezone.utc) > url_row['expires_at'] +``` + +**Redirect endpoint update**: +```python +@app.route('/') +def redirect(short_code: str): + url = get_url_from_db(short_code) # or cache + + if not url: + return "Not found", 404 + + if is_url_expired(url): + return "This link has expired", 410 # HTTP 410 Gone + + return redirect(url['original_url'], code=301) +``` + +**Cache key update** (for Decomp/001-06): +```python +# Include expiration in cached data +cache_data = { + "url": "https://...", + "expires_at": "2025-02-05T12:00:00Z", + "is_permanent": False +} +# TTL is min(cache_ttl, time_until_expiration) +``` + +## Acceptance Criteria + +- [ ] URL with past expiration returns 410 Gone +- [ ] URL with future expiration redirects normally +- [ ] Permanent URL (expires_at=NULL) never expires +- [ ] ttl_seconds parameter works correctly +- [ ] expires_at ISO 8601 format is parsed correctly +- [ ] Cache respects expiration (TTL < remaining time) +- [ ] 410 response includes helpful message + +## Notes + +**Trade-offs**: +- Hard delete vs soft delete (410): 410 chosen for better user feedback +- Immediate cleanup vs background job: Background job optional +- Default TTL: None (permanent) vs configurable default + +**Edge cases**: +- Timezone handling: All timestamps in UTC +- Clock skew: Allow 5-second grace period +- Very short TTLs: Minimum 60 seconds to prevent issues + +**Performance considerations**: +- Index on expires_at for efficient cleanup queries +- Cache expiration: set Redis TTL = min(cache_ttl, url_ttl_remaining) + +**Cleanup query** (for background job): +```sql +-- Delete URLs expired more than 30 days ago +DELETE FROM urls +WHERE expires_at < NOW() - INTERVAL '30 days' + AND is_permanent = FALSE; +``` + +**Alternatives considered**: +- Soft delete with deleted_at: rejected, 410 is sufficient +- Immediate hard delete: rejected, loses analytics data +- Cron-based cleanup: optional, can be manual initially diff --git a/ai_coder_1/subtasks/Decomp-001-09.md b/ai_coder_1/subtasks/Decomp-001-09.md new file mode 100644 index 0000000..b84b6a7 --- /dev/null +++ b/ai_coder_1/subtasks/Decomp-001-09.md @@ -0,0 +1,223 @@ +# Subtask: Analytics - Click Tracking + +**Parent Task**: Decomp/001 +**Subtask ID**: Decomp/001-09 +**Dependencies**: Decomp/001-01 (Database Schema), Decomp/001-04 (Redirect Endpoint) + +## Description + +Implement click analytics tracking for shortened URLs. Track each redirect with timestamp, user-agent, and optional geo-location. Provide aggregate statistics via API. + +## Requirements + +- Track every redirect click +- Store: timestamp, IP address, user-agent, referer, country (optional) +- Increment click count atomically +- Provide per-URL statistics API +- Provide aggregate statistics (top URLs, recent clicks) +- Privacy: optional anonymization of IP addresses +- Separate analytics database/table for performance + +## Technical Specifications + +**Database schema**: +```sql +-- Click events table (append-only, write-optimized) +CREATE TABLE clicks ( + id BIGSERIAL PRIMARY KEY, + url_id BIGINT NOT NULL REFERENCES urls(id) ON DELETE CASCADE, + clicked_at TIMESTAMP NOT NULL DEFAULT NOW(), + ip_address INET, -- IPv4/IPv6 + ip_anonymized INET, -- IP with last octet masked + user_agent TEXT, -- Full UA string + user_agent_family VARCHAR(50), -- Parsed: Chrome, Firefox, etc. + user_agent_type VARCHAR(20), -- bot, browser, mobile + referer TEXT, + country_code CHAR(2), -- ISO 3166-1 alpha-2 + city VARCHAR(100), + device_type VARCHAR(20), -- desktop, mobile, tablet + browser VARCHAR(50), + os VARCHAR(50) +); + +-- Indexes for common queries +CREATE INDEX idx_clicks_url_id ON clicks(url_id); +CREATE INDEX idx_clicks_clicked_at ON clicks(clicked_at DESC); +CREATE INDEX idx_clicks_url_time ON clicks(url_id, clicked_at DESC); + +-- Materialized view for URL stats (refreshed periodically) +CREATE MATERIALIZED VIEW url_stats AS +SELECT + url_id, + COUNT(*) AS total_clicks, + COUNT(DISTINCT ip_anonymized) AS unique_visitors, + MIN(clicked_at) AS first_click, + MAX(clicked_at) AS last_click +FROM clicks +GROUP BY url_id; + +CREATE UNIQUE INDEX ON url_stats(url_id); + +-- Denormalized click count on URLs table (for fast reads) +ALTER TABLE urls ADD COLUMN click_count BIGINT DEFAULT 0; +``` + +**Click tracking middleware**: +```python +from datetime import datetime, timezone +import hashlib +from user_agents import parse as parse_ua + +def track_click(url_id: int, request): + """ + Record click event asynchronously. + + Must be non-blocking for redirect performance. + """ + ip = request.headers.get('X-Forwarded-For', request.remote_addr) + ip_anon = anonymize_ip(ip) + + ua_string = request.headers.get('User-Agent', '') + ua = parse_ua(ua_string) + + click_data = { + 'url_id': url_id, + 'clicked_at': datetime.now(timezone.utc), + 'ip_address': ip, + 'ip_anonymized': ip_anon, + 'user_agent': ua_string[:500], # Truncate if needed + 'user_agent_family': ua.browser.family if ua.browser else None, + 'user_agent_type': 'bot' if ua.is_bot else 'browser', + 'referer': request.headers.get('Referer', '')[:500], + 'device_type': get_device_type(ua), + 'browser': f"{ua.browser.family}" if ua.browser else None, + 'os': f"{ua.os.family}" if ua.os else None, + } + + # Write to click events table (non-blocking) + # Use: background worker, message queue, or fast async write + insert_click_async(click_data) + + # Increment denormalized counter (atomic) + increment_url_click_count(url_id) + +def anonymize_ip(ip: str) -> str: + """ + Mask last octet for privacy (GDPR compliance). + + IPv4: 192.168.1.100 -> 192.168.1.0 + IPv6: mask last 80 bits + """ + import ipaddress + addr = ipaddress.ip_address(ip) + + if addr.version == 4: + # Mask last octet + masked = ipaddress.IPv4Address( + int(addr) & 0xFFFFFF00 + ) + else: + # Mask last 80 bits for IPv6 + masked = ipaddress.IPv6Address( + int(addr) & 0xFFFFFFFFFFFFFFFFFFFF + ) + + return str(masked) + +def get_device_type(ua) -> str: + """Determine device type from user agent.""" + if ua.is_mobile: + return 'mobile' + elif ua.is_tablet: + return 'tablet' + elif ua.is_pc: + return 'desktop' + return 'unknown' +``` + +**Update redirect endpoint**: +```python +@app.route('/') +def redirect(short_code: str): + url = get_url_from_db(short_code) + + if not url: + return "Not found", 404 + + # Track click BEFORE redirect (non-blocking) + track_click_async(url['id'], request) + + return redirect(url['original_url'], code=301) +``` + +**API endpoints**: +```python +# Per-URL statistics +GET /api/stats/{short_code} +Response: +{ + "short_code": "abc123", + "original_url": "https://example.com", + "created_at": "2025-02-01T00:00:00Z", + "total_clicks": 12345, + "unique_visitors": 8923, + "first_click": "2025-02-01T01:23:45Z", + "last_click": "2025-02-04T12:34:56Z", + "clicks_today": 234, + "clicks_7days": 1523, + "top_countries": [ + {"country": "US", "clicks": 4523}, + {"country": "DE", "clicks": 1823} + ], + "top_devices": [ + {"device": "mobile", "clicks": 7234}, + {"device": "desktop", "clicks": 4123} + ] +} + +# Time series data +GET /api/stats/{short_code}?by=day&days=30 +Response: +{ + "data": [ + {"date": "2025-01-15", "clicks": 234}, + {"date": "2025-01-16", "clicks": 456} + ] +} + +# Recent clicks (paginated) +GET /api/stats/{short_code}/clicks?page=1&limit=50 +``` + +## Acceptance Criteria + +- [ ] Every redirect increments click count +- [ ] Click count is accurate (no lost updates under concurrency) +- [ ] Statistics API returns correct aggregate data +- [ ] IP anonymization works for both IPv4 and IPv6 +- [ ] Analytics don't slow down redirects (<5ms overhead) +- [ ] User-agent parsing correctly identifies browsers/bots +- [ ] Materialized view refreshes successfully + +## Notes + +**Trade-offs**: +- Append-only vs aggregated clicks table: Append-only chosen for accuracy +- Synchronous vs async tracking: Async required for performance +- Full IP vs anonymized: Anonymized for GDPR compliance + +**Performance considerations**: +- Click writes must be non-blocking (use queue or separate worker) +- Consider ClickHouse/TimescaleDB for high-volume analytics +- Materialized view refresh: every 5-15 minutes +- Denormalized click_count: updated via atomic increment + +**Scalability**: +- Partition clicks table by date (monthly partitions) +- Archive old clicks to cold storage after 90 days +- Separate read replica for analytics queries + +**Alternatives considered**: +- In-memory analytics: rejected, loses data on restart +- External analytics service: rejected, requirement is self-contained +- Real-time stats: rejected, too expensive, periodic is sufficient diff --git a/ai_coder_1/subtasks/Decomp-001-10.md b/ai_coder_1/subtasks/Decomp-001-10.md new file mode 100644 index 0000000..83851fc --- /dev/null +++ b/ai_coder_1/subtasks/Decomp-001-10.md @@ -0,0 +1,268 @@ +# Subtask: Rate Limiting for Abuse Prevention + +**Parent Task**: Decomp/001 +**Subtask ID**: Decomp/001-10 +**Dependencies**: Decomp/001-04 (Redirect Endpoint), Decomp/001-06 (Caching Layer) + +## Description + +Implement rate limiting to prevent abuse of the URL shortening service. Protect against URL creation spam, excessive redirect requests, and potential DoS attacks. Use token bucket or sliding window algorithm with Redis backend. + +## Requirements + +- Rate limit URL creation endpoint (e.g., 10 requests/minute) +- Rate limit redirect endpoint (e.g., 100 requests/second per IP) +- Rate limit analytics API (e.g., 60 requests/minute) +- Configurable limits per endpoint +- IP-based and API-key-based limiting +- Return standard rate limit headers (RateLimit-* headers) +- Sliding window algorithm for accurate limiting +- Whitelist for trusted IPs/API keys + +## Technical Specifications + +**Rate limiting algorithm**: Sliding Window Log (accurate, memory-efficient) + +**Redis data structure**: +``` +# Key format: ratelimit:{endpoint}:{identifier} +# Value: sorted set of timestamps +# Score: timestamp of request +# Member: unique request ID (UUID) + +ZADD ratelimit:create:192.168.1.1 +ZREMRANGEBYSCORE ratelimit:create:192.168.1.1 0 +ZCARD ratelimit:create:192.168.1.1 +``` + +**Rate limiter implementation**: +```python +import time +import uuid +from typing import Optional, Tuple + +class RateLimiter: + """ + Sliding window rate limiter using Redis. + + Window: time interval in seconds + Limit: max requests allowed within window + """ + + def __init__(self, redis_client): + self.redis = redis_client + + def is_allowed( + self, + key: str, + limit: int, + window: int + ) -> Tuple[bool, dict]: + """ + Check if request is allowed under rate limit. + + Args: + key: Unique identifier (e.g., "create:192.168.1.1") + limit: Max requests per window + window: Time window in seconds + + Returns: + (allowed, meta) where meta contains: + - remaining: requests left in window + - reset_at: unix timestamp when limit resets + - retry_after: seconds to wait if not allowed + """ + now = time.time() + window_start = now - window + request_id = str(uuid.uuid4()) + + pipe = self.redis.pipeline() + + # Remove old entries outside the window + pipe.zremrangebyscore(key, 0, window_start) + + # Count current requests in window + pipe.zcard(key) + + # Add this request + pipe.zadd(key, {request_id: now}) + + # Set expiry on the key (cleanup) + pipe.expire(key, window + 1) + + results = pipe.execute() + current_count = results[1] + + allowed = current_count < limit + remaining = max(0, limit - current_count - 1) + reset_at = int(now + window) + retry_after = int(window - (now % window)) if not allowed else 0 + + return allowed, { + 'limit': limit, + 'remaining': remaining, + 'reset': reset_at, + 'retry_after': retry_after + } + + def get_key(self, endpoint: str, identifier: str) -> str: + """Generate Redis key for rate limiting.""" + return f"ratelimit:{endpoint}:{identifier}" +``` + +**Rate limit configuration**: +```python +RATE_LIMITS = { + # URL creation: strict to prevent spam + 'create_url': { + 'limit': 10, + 'window': 60, # per minute + 'burst': 5 # allow burst + }, + + # Redirects: generous per IP + 'redirect': { + 'limit': 100, + 'window': 1, # per second + 'burst': 20 + }, + + # Analytics API + 'analytics': { + 'limit': 60, + 'window': 60, # per minute + 'burst': 10 + }, + + # QR code generation + 'qr_code': { + 'limit': 30, + 'window': 60, # per minute + 'burst': 5 + } +} + +# Higher limits for authenticated users +AUTHENTICATED_MULTIPLIER = 10 +``` + +**Middleware decorator**: +```python +from functools import wraps +from flask import request, jsonify + +def rate_limit(endpoint: str): + """ + Decorator to apply rate limiting to an endpoint. + + Returns 429 Too Many Requests if limit exceeded. + """ + def decorator(f): + @wraps(f) + def wrapped(*args, **kwargs): + # Get identifier (IP or API key) + identifier = get_rate_limit_identifier(request) + config = RATE_LIMITS[endpoint] + + # Check if whitelisted + if is_whitelisted(identifier): + return f(*args, **kwargs) + + # Check rate limit + limiter = RateLimiter(get_redis()) + key = limiter.get_key(endpoint, identifier) + allowed, meta = limiter.is_allowed( + key, + config['limit'], + config['window'] + ) + + # Set rate limit headers + set_rate_limit_headers(meta) + + if not allowed: + response = jsonify({ + 'error': 'Rate limit exceeded', + 'retry_after': meta['retry_after'] + }) + response.status_code = 429 + response.headers['Retry-After'] = str(meta['retry_after']) + return response + + return f(*args, **kwargs) + + return wrapped + return decorator + +def get_rate_limit_identifier(request) -> str: + """Extract identifier for rate limiting.""" + # Prefer API key over IP + api_key = request.headers.get('X-API-Key') + if api_key: + return f"apikey:{api_key}" + + # Fallback to IP address + ip = request.headers.get('X-Forwarded-For', request.remote_addr) + return f"ip:{ip}" + +def set_rate_limit_headers(meta: dict): + """Set standard rate limit HTTP headers.""" + flask.response.headers['X-RateLimit-Limit'] = str(meta['limit']) + flask.response.headers['X-RateLimit-Remaining'] = str(meta['remaining']) + flask.response.headers['X-RateLimit-Reset'] = str(meta['reset']) +``` + +**Apply to endpoints**: +```python +@app.route('/api/shorten', methods=['POST']) +@rate_limit('create_url') +def create_short_url(): + ... + +@app.route('/') +@rate_limit('redirect') +def redirect(short_code: str): + ... + +@app.route('/api/stats/') +@rate_limit('analytics') +def get_stats(short_code: str): + ... +``` + +## Acceptance Criteria + +- [ ] Rate limit enforced on URL creation (10/min) +- [ ] Rate limit enforced on redirects (100/sec per IP) +- [ ] 429 response with Retry-After header when exceeded +- [ ] Rate limit headers present on all responses +- [ ] Sliding window accurately counts requests +- [ ] Whitelist bypasses rate limiting +- [ ] API keys get higher limits than anonymous IPs + +## Notes + +**Trade-offs**: +- Token bucket vs sliding window: Sliding window chosen for accuracy +- Redis vs in-memory: Redis required for distributed systems +- Per-IP vs per-user: Per-IP simpler, per-user requires authentication + +**Edge cases**: +- Multiple users behind NAT: counted as one (acceptable) +- IPv6 addresses: normalize to /64 or /48 prefix +- Distributed systems: Redis must be shared across instances + +**Performance**: +- Redis operations: O(log N) for ZADD, O(M) for ZREMRANGEBYSCORE +- Expected latency: <5ms per rate limit check +- Connection pooling required for high throughput + +**Security considerations**: +- Rate limit bypass attempts: check X-Forwarded-For chain +- DDoS protection: rate limiting is first line, not only defense +- API key exposure: don't log keys, use hash for identification + +**Alternatives considered**: +- Fixed window: rejected, allows double requests at window boundary +- Token bucket: rejected, requires more state, sliding window sufficient +- Local-only limiting: rejected, doesn't work in distributed setup diff --git a/ai_coder_1/subtasks/Decomp-001-11.md b/ai_coder_1/subtasks/Decomp-001-11.md new file mode 100644 index 0000000..6a81b61 --- /dev/null +++ b/ai_coder_1/subtasks/Decomp-001-11.md @@ -0,0 +1,363 @@ +# Subtask: URL Creation and Management API + +**Parent Task**: Decomp/001 +**Subtask ID**: Decomp/001-11 +**Dependencies**: Decomp/001-01 (Database Schema), Decomp/001-02 (Base62), Decomp/001-03 (Short Code Generation) + +## Description + +Implement REST API for creating, retrieving, updating, and deleting shortened URLs. This is the primary user-facing API that ties together the database, encoding, and code generation components. + +## Requirements + +- Create short URL from long URL +- Support custom aliases +- Retrieve URL details (metadata) +- Update existing URLs +- Delete URLs (soft delete) +- Batch URL creation +- Input validation and error handling +- API authentication (optional API key) + +## Technical Specifications + +**Base URL**: `/api/v1/` + +**Data models**: +```python +from datetime import datetime +from typing import Optional +from pydantic import BaseModel, HttpUrl, Field + +class CreateURLRequest(BaseModel): + """Request to create a shortened URL.""" + url: HttpUrl = Field(..., description="Original URL to shorten") + custom_alias: Optional[str] = Field( + None, + min_length=3, + max_length=20, + pattern=r'^[a-zA-Z0-9-_]+$', + description="Custom short code (optional)" + ) + ttl_seconds: Optional[int] = Field( + None, + gt=0, + le=31536000, # Max 1 year + description="Time-to-live in seconds" + ) + expires_at: Optional[datetime] = Field( + None, + description="Absolute expiration timestamp" + ) + permanent: Optional[bool] = Field( + False, + description="If true, URL never expires" + ) + metadata: Optional[dict] = Field( + None, + description="Custom metadata for URL" + ) + +class URLResponse(BaseModel): + """Response with URL details.""" + short_code: str + short_url: str + original_url: str + created_at: datetime + expires_at: Optional[datetime] + is_permanent: bool + click_count: int + custom_alias: bool + qr_code_url: str + +class UpdateURLRequest(BaseModel): + """Request to update an existing URL.""" + url: Optional[HttpUrl] = None + expires_at: Optional[datetime] = None + permanent: Optional[bool] = None + metadata: Optional[dict] = None + +class BatchCreateRequest(BaseModel): + """Request to create multiple URLs.""" + urls: list[CreateURLRequest] + Field(..., min_length=1, max_length=100) +``` + +**API endpoints**: + +```python +from flask import Flask, request, jsonify +from http import HTTPStatus + +app = Flask(__name__) + +# POST /api/v1/shorten - Create short URL +@app.route('/api/v1/shorten', methods=['POST']) +@rate_limit('create_url') +def create_short_url(): + """ + Create a new shortened URL. + + Request: + { + "url": "https://example.com/very/long/path", + "custom_alias": "mylink", // optional + "ttl_seconds": 86400, // optional + "permanent": false // optional + } + + Response 201: + { + "short_code": "abc123", + "short_url": "https://sh.rt/abc123", + "original_url": "https://example.com/very/long/path", + "created_at": "2025-02-04T12:00:00Z", + "expires_at": "2025-02-05T12:00:00Z", + "is_permanent": false, + "click_count": 0, + "custom_alias": false, + "qr_code_url": "https://sh.rt/qr/abc123" + } + + Errors: + - 400: Invalid input + - 409: Custom alias already exists + - 422: Unprocessable entity (invalid URL) + - 429: Rate limit exceeded + """ + try: + data = CreateURLRequest(**request.get_json()) + except ValidationError as e: + return jsonify({'error': 'Validation failed', 'details': e.errors()}), 400 + + # Check for duplicate URL (if enabled) + existing = find_duplicate_url(data.url) + if existing: + return jsonify(URLResponse.from_db_row(existing)), 200 # Already exists + + # Handle custom alias + if data.custom_alias: + if not is_alias_available(data.custom_alias): + return jsonify({ + 'error': 'Custom alias already taken', + 'alias': data.custom_alias + }), 409 + short_code = data.custom_alias + else: + # Generate unique short code + short_code = generate_unique_short_code() + + # Calculate expiration + expires_at = calculate_expiration( + ttl_seconds=data.ttl_seconds, + expires_at=data.expires_at, + permanent=data.permanent + ) + + # Store in database + url_id = insert_url( + short_code=short_code, + original_url=str(data.url), + expires_at=expires_at, + is_permanent=data.permanent or expires_at is None, + custom_alias=bool(data.custom_alias), + metadata=data.metadata + ) + + # Build response + response = URLResponse( + short_code=short_code, + short_url=f"{BASE_URL}/{short_code}", + original_url=str(data.url), + created_at=datetime.now(timezone.utc), + expires_at=expires_at, + is_permanent=data.permanent or expires_at is None, + click_count=0, + custom_alias=bool(data.custom_alias), + qr_code_url=f"{BASE_URL}/qr/{short_code}" + ) + + return jsonify(response.dict()), 201 + + +# GET /api/v1/urls/:short_code - Get URL details +@app.route('/api/v1/urls/', methods=['GET']) +@rate_limit('analytics') +def get_url_details(short_code: str): + """ + Retrieve details for a shortened URL. + + Response 200: URLResponse object + Response 404: URL not found + """ + url = get_url_by_short_code(short_code) + if not url: + return jsonify({'error': 'URL not found'}), 404 + + return jsonify(URLResponse.from_db_row(url)), 200 + + +# PUT /api/v1/urls/:short_code - Update URL +@app.route('/api/v1/urls/', methods=['PUT']) +@rate_limit('create_url') # Same limits as creation +def update_url(short_code: str): + """ + Update an existing URL. + + Request: Partial UpdateURLRequest + + Note: Cannot change short_code once created. + + Response 200: Updated URLResponse + Response 404: URL not found + """ + url = get_url_by_short_code(short_code) + if not url: + return jsonify({'error': 'URL not found'}), 404 + + data = UpdateURLRequest(**request.get_json()) + + # Apply updates + updates = {} + if data.url: + updates['original_url'] = str(data.url) + if data.expires_at is not None: + updates['expires_at'] = data.expires_at + if data.permanent is not None: + updates['is_permanent'] = data.permanent + if data.metadata is not None: + updates['metadata'] = data.metadata + + if updates: + update_url_in_db(url['id'], updates) + # Invalidate cache + invalidate_cache(short_code) + + return jsonify(URLResponse.from_db_row(get_url_by_short_code(short_code))), 200 + + +# DELETE /api/v1/urls/:short_code - Delete URL +@app.route('/api/v1/urls/', methods=['DELETE']) +@rate_limit('create_url') +def delete_url(short_code: str): + """ + Delete a shortened URL (soft delete). + + Response 204: No content (success) + Response 404: URL not found + """ + url = get_url_by_short_code(short_code) + if not url: + return jsonify({'error': 'URL not found'}), 404 + + # Soft delete: mark as deleted + soft_delete_url(url['id']) + + # Invalidate cache + invalidate_cache(short_code) + + return '', 204 + + +# POST /api/v1/shorten/batch - Batch create URLs +@app.route('/api/v1/shorten/batch', methods=['POST']) +@rate_limit('create_url') # Higher limit for batch +def create_short_urls_batch(): + """ + Create multiple shortened URLs in one request. + + Request: + { + "urls": [ + {"url": "https://example1.com"}, + {"url": "https://example2.com", "custom_alias": "link2"} + ] + } + + Response 201: + { + "urls": [URLResponse, ...], + "failed": [ + {"index": 0, "error": "reason"} + ] + } + + Allows partial success: some URLs may fail while others succeed. + """ + data = BatchCreateRequest(**request.get_json()) + + results = [] + failed = [] + + for i, url_req in enumerate(data.urls): + try: + # Create URL (reuse logic from single create) + result = create_single_url(url_req) + results.append(result) + except Exception as e: + failed.append({ + 'index': i, + 'url': str(url_req.url), + 'error': str(e) + }) + + return jsonify({ + 'urls': results, + 'failed': failed + }), 201 if results and not failed else 207 # 207 for multi-status +``` + +**Validation helper**: +```python +def is_alias_available(alias: str) -> bool: + """Check if custom alias is not already taken.""" + return not url_exists_by_short_code(alias) + +def find_duplicate_url(url: str) -> Optional[dict]: + """ + Find existing URL with same target (deduplication). + + Can be disabled via config if not desired. + """ + if not ENABLE_DEDUPLICATION: + return None + return get_url_by_original_url(url) +``` + +## Acceptance Criteria + +- [ ] Create URL returns valid short code +- [ ] Custom alias works when available +- [ ] Custom alias rejected when taken (409) +- [ ] Duplicate URL detection returns existing URL +- [ ] Update endpoint modifies only specified fields +- [ ] Delete endpoint soft-deletes URL +- [ ] Batch create handles partial failures +- [ ] All endpoints return proper HTTP status codes + +## Notes + +**Trade-offs**: +- Duplicate detection: Optional, may not be desired in all cases +- Soft delete vs hard delete: Soft preserves analytics +- Synchronous vs async creation: Synchronous for immediate feedback + +**Edge cases**: +- Very long original URLs: Truncate at DB limit (2048 chars) +- Custom alias collision: Return helpful error message +- Concurrent creation of same alias: Second request fails + +**Performance**: +- Index on short_code for O(1) lookups +- Index on original_url hash for duplicate detection +- Cache invalidation on update/delete + +**Security**: +- URL validation: Prevent javascript: and data: schemes +- Rate limiting: Applied to all write operations +- Input sanitization: Escape HTML in metadata + +**Alternatives considered**: +- Hard delete: Rejected, loses analytics +- Async creation: Rejected, adds complexity +- No duplicate detection: Default to disabled diff --git a/ai_coder_1/subtasks/Decomp-002-01.md b/ai_coder_1/subtasks/Decomp-002-01.md new file mode 100644 index 0000000..26884fb --- /dev/null +++ b/ai_coder_1/subtasks/Decomp-002-01.md @@ -0,0 +1,248 @@ +# Subtask: Database Schema for Chat Service + +**Parent Task**: Decomp/002 +**Subtask ID**: Decomp/002-01 +**Dependencies**: None + +## Description + +Design and implement database schema for real-time chat service supporting users, servers, channels, messages, and presence. Schema must support high write throughput (100K concurrent users) and efficient pagination for message history. + +## Requirements + +- Store users with profile information +- Store servers/guilds (like Discord) +- Store channels within servers +- Store messages with metadata +- Store user presence (online/offline/away) +- Support message threading/replies +- Support message reactions +- Store file attachments metadata +- Efficient pagination for message history +- Indexes for common query patterns + +## Technical Specifications + +**Database choice**: PostgreSQL (for ACID, JSONB, full-text search) + +**Schema definition**: +```sql +-- Users table +CREATE TABLE users ( + id BIGSERIAL PRIMARY KEY, + username VARCHAR(32) NOT NULL UNIQUE, + email VARCHAR(255) NOT NULL UNIQUE, + password_hash VARCHAR(255) NOT NULL, + display_name VARCHAR(100), + avatar_url TEXT, + bio TEXT, + created_at TIMESTAMP NOT NULL DEFAULT NOW(), + updated_at TIMESTAMP NOT NULL DEFAULT NOW(), + is_active BOOLEAN NOT NULL DEFAULT TRUE, + last_seen_at TIMESTAMP +); + +CREATE INDEX idx_users_username ON users(username); +CREATE INDEX idx_users_email ON users(email); +CREATE INDEX idx_users_last_seen ON users(last_seen_at); + +-- Servers/Guilds table +CREATE TABLE servers ( + id BIGSERIAL PRIMARY KEY, + name VARCHAR(100) NOT NULL, + owner_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + icon_url TEXT, + description TEXT, + created_at TIMESTAMP NOT NULL DEFAULT NOW(), + updated_at TIMESTAMP NOT NULL DEFAULT NOW(), + max_members INTEGER DEFAULT 100000, + region VARCHAR(10) +); + +CREATE INDEX idx_servers_owner ON servers(owner_id); + +-- Server members (many-to-many with roles) +CREATE TABLE server_members ( + id BIGSERIAL PRIMARY KEY, + server_id BIGINT NOT NULL REFERENCES servers(id) ON DELETE CASCADE, + user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + nickname VARCHAR(100), + joined_at TIMESTAMP NOT NULL DEFAULT NOW(), + roles JSONB DEFAULT '[]'::jsonb, + UNIQUE(server_id, user_id) +); + +CREATE INDEX idx_server_members_server ON server_members(server_id); +CREATE INDEX idx_server_members_user ON server_members(user_id); + +-- Channels table +CREATE TABLE channels ( + id BIGSERIAL PRIMARY KEY, + server_id BIGINT REFERENCES servers(id) ON DELETE CASCADE, -- NULL for DMs + type VARCHAR(20) NOT NULL, -- 'text', 'voice', 'dm', 'category' + name VARCHAR(100) NOT NULL, + position INTEGER DEFAULT 0, + topic TEXT, + is_nsfw BOOLEAN DEFAULT FALSE, + slowmode_seconds INTEGER DEFAULT 0, + created_at TIMESTAMP NOT NULL DEFAULT NOW(), + updated_at TIMESTAMP NOT NULL DEFAULT NOW(), + parent_id BIGINT REFERENCES channels(id) -- For categories +); + +CREATE INDEX idx_channels_server ON channels(server_id); +CREATE INDEX idx_channels_type ON channels(type); +CREATE INDEX idx_channels_parent ON channels(parent_id); + +-- Direct message channels +CREATE TABLE dm_channels ( + id BIGSERIAL PRIMARY KEY, + type VARCHAR(20) NOT NULL, -- 'dm' (2 users), 'group_dm' (3+ users) + created_at TIMESTAMP NOT NULL DEFAULT NOW() +); + +CREATE TABLE dm_channel_members ( + channel_id BIGINT NOT NULL REFERENCES dm_channels(id) ON DELETE CASCADE, + user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + joined_at TIMESTAMP NOT NULL DEFAULT NOW(), + UNIQUE(channel_id, user_id) +); + +CREATE INDEX idx_dm_members_channel ON dm_channel_members(channel_id); +CREATE INDEX idx_dm_members_user ON dm_channel_members(user_id); + +-- Messages table (partitioned by month for scalability) +CREATE TABLE messages ( + id BIGSERIAL PRIMARY KEY, + channel_id BIGINT NOT NULL REFERENCES channels(id) ON DELETE CASCADE, + author_id BIGINT NOT NULL REFERENCES users(id) ON DELETE SET NULL, + content TEXT NOT NULL, + type VARCHAR(20) DEFAULT 'default', -- 'default', 'reply', 'system' + reply_to_id BIGINT REFERENCES messages(id) ON DELETE SET NULL, + created_at TIMESTAMP NOT NULL DEFAULT NOW(), + updated_at TIMESTAMP NOT NULL DEFAULT NOW(), + edited_at TIMESTAMP, + is_pinned BOOLEAN DEFAULT FALSE, + metadata JSONB DEFAULT '{}'::jsonb, -- For extensions + mentions JSONB DEFAULT '[]'::jsonb, -- Array of user IDs + -- Denormalized for pagination + channel_position BIGINT NOT NULL -- Per-channel sequence number +); + +-- Partition messages by month +CREATE TABLE messages_2025_02 PARTITION OF messages + FOR VALUES FROM ('2025-02-01') TO ('2025-03-01'); + +CREATE INDEX idx_messages_channel ON messages(channel_id, channel_position DESC); +CREATE INDEX idx_messages_author ON messages(author_id); +CREATE INDEX idx_messages_created ON messages(created_at DESC); +CREATE INDEX idx_messages_reply_to ON messages(reply_to_id); +CREATE INDEX idx_messages_mentions ON messages USING GIN(mentions); +CREATE INDEX idx_messages_fts ON messages USING GIN(to_tsvector('english', content)); + +-- Message reactions +CREATE TABLE message_reactions ( + id BIGSERIAL PRIMARY KEY, + message_id BIGINT NOT NULL REFERENCES messages(id) ON DELETE CASCADE, + user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + emoji VARCHAR(100) NOT NULL, -- Unicode or custom emoji ID + emoji_type VARCHAR(10) DEFAULT 'unicode', -- 'unicode', 'custom' + created_at TIMESTAMP NOT NULL DEFAULT NOW(), + UNIQUE(message_id, user_id, emoji) +); + +CREATE INDEX idx_reactions_message ON message_reactions(message_id); +CREATE INDEX idx_reactions_user ON message_reactions(user_id); + +-- User presence +CREATE TABLE user_presence ( + user_id BIGINT PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE, + status VARCHAR(20) NOT NULL DEFAULT 'offline', -- 'online', 'idle', 'dnd', 'offline' + last_updated TIMESTAMP NOT NULL DEFAULT NOW(), + active_device_id VARCHAR(100), -- Socket ID for connection tracking + activities JSONB DEFAULT '[]'::jsonb -- Playing X, listening to Y +); + +CREATE INDEX idx_presence_status ON user_presence(status); +CREATE INDEX idx_presence_updated ON user_presence(last_updated); + +-- File attachments +CREATE TABLE attachments ( + id BIGSERIAL PRIMARY KEY, + message_id BIGINT NOT NULL REFERENCES messages(id) ON DELETE CASCADE, + filename VARCHAR(255) NOT NULL, + content_type VARCHAR(100) NOT NULL, + size_bytes BIGINT NOT NULL, + storage_path TEXT NOT NULL, -- S3 key or local path + width INTEGER, -- For images/videos + height INTEGER, + duration_seconds INTEGER, -- For audio/video + is_spoiler BOOLEAN DEFAULT FALSE, + created_at TIMESTAMP NOT NULL DEFAULT NOW() +); + +CREATE INDEX idx_attachments_message ON attachments(message_id); +CREATE INDEX idx_attachments_type ON attachments(content_type); + +-- Read receipts (optional, for read status) +CREATE TABLE channel_read_state ( + user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + channel_id BIGINT NOT NULL REFERENCES channels(id) ON DELETE CASCADE, + last_read_message_id BIGINT NOT NULL REFERENCES messages(id), + last_read_at TIMESTAMP NOT NULL DEFAULT NOW(), + mention_count INTEGER DEFAULT 0, + UNIQUE(user_id, channel_id) +); + +CREATE INDEX idx_read_state_user_channel ON channel_read_state(user_id, channel_id); +``` + +**Partition management**: +```sql +-- Function to create monthly partitions +CREATE OR REPLACE FUNCTION create_monthly_partition(month_date DATE) +RETURNS VOID AS $$ +DECLARE + partition_name TEXT; + start_date TEXT; + end_date TEXT; +BEGIN + partition_name := 'messages_' || to_char(month_date, 'YYYY_MM'); + start_date := to_char(month_date, 'YYYY-MM-DD'); + end_date := to_char(month_date + INTERVAL '1 month', 'YYYY-MM-DD'); + + EXECUTE format( + 'CREATE TABLE IF NOT EXISTS %I PARTITION OF messages + FOR VALUES FROM (%L) TO (%L)', + partition_name, start_date, end_date + ); +END; +$$ LANGUAGE plpgsql; +``` + +## Acceptance Criteria + +- [ ] All tables created without errors +- [ ] Foreign key constraints enforced +- [ ] Unique constraints prevent duplicates +- [ ] Partitioning allows efficient time-based queries +- [ ] Indexes support common query patterns +- [ ] JSONB fields enable flexible metadata storage +- [ ] Full-text search index on message content + +## Notes + +**Trade-offs**: +- PostgreSQL vs MongoDB: PostgreSQL chosen for ACID guarantees and mature tooling +- Partitioning by month: Balances partition count with query efficiency +- Channel position denormalization: Speeds up pagination at cost of write complexity + +**Scalability considerations**: +- Messages table grows fastest — partitioning essential +- Consider archive for messages older than 6 months +- Read receipts can be moved to separate database (Redis) + +**Alternatives considered**: +- Single messages table: Rejected, doesn't scale to billions of messages +- NoSQL document store: Rejected, complex queries (mentions, reactions) harder +- Separate DB per server: Rejected, too complex for initial implementation diff --git a/ai_coder_1/subtasks/Decomp-002-02.md b/ai_coder_1/subtasks/Decomp-002-02.md new file mode 100644 index 0000000..2052a83 --- /dev/null +++ b/ai_coder_1/subtasks/Decomp-002-02.md @@ -0,0 +1,366 @@ +# Subtask: WebSocket Connection Manager + +**Parent Task**: Decomp/002 +**Subtask ID**: Decomp/002-02 +**Dependencies**: None + +## Description + +Implement WebSocket connection manager supporting 100K concurrent connections. Handle connection lifecycle, heartbeats, reconnection, and message routing. Supports multiple connections per user (multiple devices). + +## Requirements + +- Accept WebSocket connections on `/ws` +- Authenticate connections via token +- Handle multiple connections per user +- Heartbeat/ping-pong to detect dead connections +- Graceful connection cleanup +- Support both WebSocket and HTTP fallback (SSE) +- Rate limit connection attempts +- Track connection state (connected, connecting, disconnected) + +## Technical Specifications + +**WebSocket library**: `websockets` (Python) or `socket.io` (Node.js) — Python assumed + +**Connection manager**: +```python +import asyncio +import json +import logging +from datetime import datetime, timedelta +from typing import Dict, Set, Optional +from dataclasses import dataclass, field + +logger = logging.getLogger(__name__) + +@dataclass +class ConnectionState: + """State for a single WebSocket connection.""" + connection_id: str + user_id: int + socket: WebSocketServerProtocol + connected_at: datetime = field(default_factory=datetime.utcnow) + last_ping: datetime = field(default_factory=datetime.utcnow) + channels: Set[int] = field(default_factory=set) # Subscribed channel IDs + device_type: str = "unknown" # desktop, mobile, web + is_authenticated: bool = False + +class WebSocketManager: + """ + Manages WebSocket connections with support for multiple devices per user. + """ + + def __init__(self): + # connection_id -> ConnectionState + self.connections: Dict[str, ConnectionState] = {} + + # user_id -> set of connection_ids + self.user_connections: Dict[int, Set[str]] = {} + + # channel_id -> set of connection_ids (for broadcasting) + self.channel_subscribers: Dict[int, Set[str]] = {} + + self._heartbeat_task: Optional[asyncio.Task] = None + self._heartbeat_interval = 30 # seconds + self._connection_timeout = 90 # seconds + + async def connect( + self, + websocket: WebSocketServerProtocol, + token: str, + device_type: str = "unknown" + ) -> Optional[ConnectionState]: + """ + Accept and authenticate new WebSocket connection. + + Returns ConnectionState if successful, None if authentication fails. + """ + connection_id = generate_connection_id() + + # Authenticate token + user_id = await self._authenticate_token(token) + if not user_id: + await websocket.close(code=4008, reason="Invalid token") + return None + + # Create connection state + state = ConnectionState( + connection_id=connection_id, + user_id=user_id, + socket=websocket, + device_type=device_type, + is_authenticated=True + ) + + # Register connection + self.connections[connection_id] = state + if user_id not in self.user_connections: + self.user_connections[user_id] = set() + self.user_connections[user_id].add(connection_id) + + # Update user presence + await self._update_presence(user_id, "online") + + logger.info(f"Connection {connection_id} established for user {user_id}") + + return state + + async def disconnect(self, connection_id: str): + """Remove connection and update presence if user has no other connections.""" + if connection_id not in self.connections: + return + + state = self.connections[connection_id] + user_id = state.user_id + + # Unsubscribe from all channels + for channel_id in state.channels: + await self.unsubscribe(connection_id, channel_id) + + # Remove from user's connections + self.user_connections[user_id].discard(connection_id) + if not self.user_connections[user_id]: + # User has no more connections, go offline + await self._update_presence(user_id, "offline") + del self.user_connections[user_id] + + # Remove connection + del self.connections[connection_id] + + logger.info(f"Connection {connection_id} closed for user {user_id}") + + async def subscribe(self, connection_id: str, channel_id: int): + """Subscribe connection to channel for message broadcasts.""" + if connection_id not in self.connections: + return + + state = self.connections[connection_id] + state.channels.add(channel_id) + + if channel_id not in self.channel_subscribers: + self.channel_subscribers[channel_id] = set() + self.channel_subscribers[channel_id].add(connection_id) + + # Send channel join confirmation + await self.send_to_connection(connection_id, { + "type": "CHANNEL_SUBSCRIBED", + "channel_id": channel_id + }) + + async def unsubscribe(self, connection_id: str, channel_id: int): + """Unsubscribe connection from channel.""" + if connection_id not in self.connections: + return + + state = self.connections[connection_id] + state.channels.discard(channel_id) + + if channel_id in self.channel_subscribers: + self.channel_subscribers[channel_id].discard(connection_id) + if not self.channel_subscribers[channel_id]: + del self.channel_subscribers[channel_id] + + async def send_to_connection( + self, + connection_id: str, + data: dict + ) -> bool: + """Send message to specific connection. Returns False if send fails.""" + if connection_id not in self.connections: + return False + + state = self.connections[connection_id] + try: + await state.socket.send(json.dumps(data)) + return True + except Exception as e: + logger.warning(f"Failed to send to {connection_id}: {e}") + await self.disconnect(connection_id) + return False + + async def broadcast_to_channel( + self, + channel_id: int, + data: dict, + exclude_connection: Optional[str] = None + ) -> int: + """Broadcast message to all subscribers of a channel. Returns count of successful sends.""" + if channel_id not in self.channel_subscribers: + return 0 + + subscribers = self.channel_subscribers[channel_id].copy() + + # Send to all subscribers concurrently + tasks = [] + for conn_id in subscribers: + if conn_id != exclude_connection: + tasks.append(self.send_to_connection(conn_id, data)) + + results = await asyncio.gather(*tasks, return_exceptions=True) + successful = sum(1 for r in results if r is True) + + return successful + + async def send_to_user(self, user_id: int, data: dict) -> int: + """Send message to all connections for a user. Returns count of successful sends.""" + if user_id not in self.user_connections: + return 0 + + connection_ids = self.user_connections[user_id].copy() + tasks = [self.send_to_connection(cid, data) for cid in connection_ids] + results = await asyncio.gather(*tasks, return_exceptions=True) + return sum(1 for r in results if r is True) + + async def handle_message( + self, + connection_id: str, + message: str + ): + """Handle incoming message from client.""" + try: + data = json.loads(message) + msg_type = data.get("type") + + if msg_type == "PING": + await self._handle_ping(connection_id) + elif msg_type == "SUBSCRIBE": + await self.subscribe(connection_id, data["channel_id"]) + elif msg_type == "UNSUBSCRIBE": + await self.unsubscribe(connection_id, data["channel_id"]) + elif msg_type == "MESSAGE": + await self._handle_chat_message(connection_id, data) + elif msg_type == "TYPING_START": + await self._handle_typing_indicator(connection_id, data) + else: + logger.warning(f"Unknown message type: {msg_type}") + + except json.JSONDecodeError: + logger.warning(f"Invalid JSON from {connection_id}") + except Exception as e: + logger.error(f"Error handling message from {connection_id}: {e}") + + async def _handle_ping(self, connection_id: str): + """Respond to client ping.""" + if connection_id in self.connections: + state = self.connections[connection_id] + state.last_ping = datetime.utcnow() + await self.send_to_connection(connection_id, {"type": "PONG"}) + + async def _heartbeat_loop(self): + """Periodic heartbeat to detect dead connections.""" + while True: + now = datetime.utcnow() + timeout = timedelta(seconds=self._connection_timeout) + + dead_connections = [] + for conn_id, state in self.connections.items(): + if now - state.last_ping > timeout: + dead_connections.append(conn_id) + else: + # Send periodic ping + try: + await state.socket.ping() + except: + dead_connections.append(conn_id) + + # Cleanup dead connections + for conn_id in dead_connections: + await self.disconnect(conn_id) + + await asyncio.sleep(self._heartbeat_interval) + + async def start_heartbeat(self): + """Start heartbeat background task.""" + if self._heartbeat_task is None: + self._heartbeat_task = asyncio.create_task(self._heartbeat_loop()) + + async def _authenticate_token(self, token: str) -> Optional[int]: + """Validate JWT token and return user_id.""" + try: + payload = jwt.decode(token, SECRET_KEY, algorithms=["HS256"]) + return payload.get("user_id") + except jwt.InvalidTokenError: + return None + + async def _update_presence(self, user_id: int, status: str): + """Update user presence in database.""" + await db.execute( + """INSERT INTO user_presence (user_id, status, last_updated) + VALUES ($1, $2, NOW()) + ON CONFLICT (user_id) DO UPDATE + SET status = $2, last_updated = NOW()""", + user_id, status + ) + + def get_connection_stats(self) -> dict: + """Return connection statistics.""" + return { + "total_connections": len(self.connections), + "unique_users": len(self.user_connections), + "channels_with_subscribers": len(self.channel_subscribers), + "avg_connections_per_user": ( + len(self.connections) / len(self.user_connections) + if self.user_connections else 0 + ) + } +``` + +**WebSocket endpoint**: +```python +from fastapi import WebSocket, WebSocketDisconnect + +@app.websocket("/ws") +async def websocket_endpoint(websocket: WebSocket): + """Main WebSocket endpoint.""" + await websocket.accept() + + # Get token from query param + token = websocket.query_params.get("token") + if not token: + await websocket.close(code=4008, reason="Missing token") + return + + # Get device type from headers + device_type = websocket.headers.get("User-Agent", "unknown") + + # Connect + state = await manager.connect(websocket, token, device_type) + if not state: + return + + try: + while True: + message = await websocket.receive_text() + await manager.handle_message(state.connection_id, message) + + except WebSocketDisconnect: + await manager.disconnect(state.connection_id) + except Exception as e: + logger.error(f"WebSocket error: {e}") + await manager.disconnect(state.connection_id) +``` + +## Acceptance Criteria + +- [ ] WebSocket connection accepted with valid token +- [ ] Invalid token rejected with code 4008 +- [ ] Multiple connections per user supported +- [ ] Heartbeats detect dead connections +- [ ] Channel subscription/unsubscription works +- [ ] Messages broadcast to channel subscribers +- [ ] Connection cleanup on disconnect + +## Notes + +**Trade-offs**: +- In-memory state vs Redis: In-memory for simplicity, add Redis for multi-server +- Ping interval: 30s balances early detection vs overhead + +**Scalability**: +- For multi-server deployments, use Redis Pub/Sub for cross-server messaging +- Consider connection pooling and load balancing + +**Alternatives considered**: +- Socket.IO: Rejected, adds unnecessary abstraction layer +- HTTP polling: Rejected, too much overhead for real-time diff --git a/ai_coder_1/subtasks/Decomp-002-03.md b/ai_coder_1/subtasks/Decomp-002-03.md new file mode 100644 index 0000000..6f405f3 --- /dev/null +++ b/ai_coder_1/subtasks/Decomp-002-03.md @@ -0,0 +1,392 @@ +# Subtask: Message Delivery and Persistence + +**Parent Task**: Decomp/002 +**Subtask ID**: Decomp/002-03 +**Dependencies**: Decomp/002-01 (Database Schema), Decomp/002-02 (WebSocket Manager) + +## Description + +Implement message delivery pipeline with persistence to database. Handle message ordering, ACKs for delivery confirmation, and offline message queue. Support different message types (text, embed, system). + +## Requirements + +- Persist messages to database on receipt +- Broadcast messages to channel subscribers +- Track message delivery status (sent, delivered, read) +- Handle message ordering (per-channel sequence) +- Support message editing and deletion +- Offline message queue (deliver on reconnect) +- Message validation and sanitization + +## Technical Specifications + +**Message pipeline flow**: +``` +Client → WebSocket → Validate → Persist → Broadcast → ACK +``` + +**Message handler**: +```python +import asyncio +from datetime import datetime, timezone +from typing import Optional, Dict, Any +import html +import re + +class MessageHandler: + """Handle message lifecycle from receipt to delivery.""" + + def __init__(self, ws_manager: WebSocketManager, db_pool): + self.ws_manager = ws_manager + self.db = db_pool + self.message_queue = asyncio.Queue(maxsize=10000) + self._worker_task: Optional[asyncio.Task] = None + + async def start(self): + """Start message processing worker.""" + self._worker_task = asyncio.create_task(self._process_messages()) + + async def handle_incoming_message( + self, + connection_id: str, + data: dict + ) -> Optional[dict]: + """ + Handle incoming message from client. + + Returns message dict if successful, None if failed. + """ + # Validate + validation_error = self._validate_message(data) + if validation_error: + await self.ws_manager.send_to_connection(connection_id, { + "type": "ERROR", + "error": validation_error + }) + return None + + # Extract fields + channel_id = data["channel_id"] + author_id = self.ws_manager.connections[connection_id].user_id + content = data["content"] + nonce = data.get("nonce") # Client-provided deduplication ID + reply_to_id = data.get("reply_to_id") + + # Check permissions + if not await self._can_send_to_channel(author_id, channel_id): + await self.ws_manager.send_to_connection(connection_id, { + "type": "ERROR", + "error": "No permission to send to this channel" + }) + return None + + # Handle rate limiting (slowmode) + if not await self._check_slowmode(author_id, channel_id): + await self.ws_manager.send_to_connection(connection_id, { + "type": "ERROR", + "error": "Slowmode active" + }) + return None + + # Deduplication check (if nonce provided) + if nonce and await self._is_duplicate(nonce): + return None + + # Process message + message_data = await self._create_message( + channel_id=channel_id, + author_id=author_id, + content=content, + nonce=nonce, + reply_to_id=reply_to_id, + type=data.get("type", "default"), + metadata=data.get("metadata", {}), + mentions=data.get("mentions", []) + ) + + # Queue for broadcast + await self.message_queue.put(message_data) + + return message_data + + async def _create_message( + self, + channel_id: int, + author_id: int, + content: str, + nonce: Optional[str] = None, + reply_to_id: Optional[int] = None, + type: str = "default", + metadata: dict = None, + mentions: list = None + ) -> dict: + """Persist message to database.""" + async with self.db.acquire() as conn: + # Get next channel position for ordering + channel_position = await conn.fetchval( + """SELECT COALESCE(MAX(channel_position), 0) + 1 + FROM messages WHERE channel_id = $1""", + channel_id + ) + + # Insert message + message_id = await conn.fetchval( + """INSERT INTO messages + (channel_id, author_id, content, type, reply_to_id, + channel_position, metadata, mentions, created_at) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, NOW()) + RETURNING id""", + channel_id, author_id, content, type, reply_to_id, + channel_position, metadata or {}, mentions or [] + ) + + # Get full message data + message = await conn.fetchrow( + """SELECT m.*, u.username, u.display_name, u.avatar_url + FROM messages m + JOIN users u ON m.author_id = u.id + WHERE m.id = $1""", + message_id + ) + + return { + "id": str(message["id"]), + "channel_id": str(channel_id), + "author": { + "id": str(message["author_id"]), + "username": message["username"], + "display_name": message["display_name"], + "avatar_url": message["avatar_url"] + }, + "content": message["content"], + "type": message["type"], + "reply_to_id": str(message["reply_to_id"]) if message["reply_to_id"] else None, + "created_at": message["created_at"].isoformat(), + "edited_at": message["edited_at"].isoformat() if message["edited_at"] else None, + "channel_position": message["channel_position"], + "nonce": nonce + } + + async def _process_messages(self): + """Background worker to broadcast messages.""" + while True: + try: + message_data = await self.message_queue.get() + + # Broadcast to channel subscribers + await self.ws_manager.broadcast_to_channel( + int(message_data["channel_id"]), + { + "type": "MESSAGE_CREATE", + "data": message_data + } + ) + + # Send to offline users (store in offline queue) + await self._queue_for_offline_users(message_data) + + # Update read receipts for mentions + if message_data.get("mentions"): + await self._notify_mentioned_users(message_data) + + except Exception as e: + logger.error(f"Error processing message: {e}") + + def _validate_message(self, data: dict) -> Optional[str]: + """Validate incoming message.""" + required_fields = ["channel_id", "content"] + for field in required_fields: + if field not in data: + return f"Missing required field: {field}" + + content = data["content"] + + # Length validation + if len(content) > 4000: + return "Message too long (max 4000 characters)" + + if len(content) == 0: + return "Message cannot be empty" + + # Sanitize content (prevent XSS) + # Keep simple: HTML escape, remove script tags + if " bool: + """Check if user can send to channel.""" + async with self.db.acquire() as conn: + # Check if user is member of server (for server channels) + server_id = await conn.fetchval( + """SELECT server_id FROM channels WHERE id = $1""", + channel_id + ) + + if server_id: + # Server channel - check membership + return await conn.fetchval( + """SELECT 1 FROM server_members + WHERE server_id = $1 AND user_id = $2""", + server_id, user_id + ) is not None + else: + # DM channel - check if user is member + return await conn.fetchval( + """SELECT 1 FROM dm_channel_members + WHERE channel_id = $1 AND user_id = $2""", + channel_id, user_id + ) is not None + + async def _check_slowmode(self, user_id: int, channel_id: int) -> bool: + """Check slowmode restriction.""" + async with self.db.acquire() as conn: + slowmode_seconds = await conn.fetchval( + """SELECT slowmode_seconds FROM channels WHERE id = $1""", + channel_id + ) + + if not slowmode_seconds or slowmode_seconds == 0: + return True + + # Check last message time + last_message_time = await conn.fetchval( + """SELECT MAX(created_at) FROM messages + WHERE channel_id = $1 AND author_id = $2""", + channel_id, user_id + ) + + if not last_message_time: + return True + + elapsed = (datetime.now(timezone.utc) - last_message_time).total_seconds() + return elapsed >= slowmode_seconds + + async def _is_duplicate(self, nonce: str) -> bool: + """Check if message with this nonce was already processed.""" + # Could use Redis for this + return False + + async def _queue_for_offline_users(self, message_data: dict): + """Store message for offline delivery to mentioned users.""" + # Implementation: store in Redis or DB + pass + + async def _notify_mentioned_users(self, message_data: dict): + """Send notification to mentioned users.""" + # Increment mention count in read_state + pass + + async def edit_message( + self, + message_id: int, + author_id: int, + new_content: str + ) -> Optional[dict]: + """Edit an existing message.""" + async with self.db.acquire() as conn: + # Verify ownership + message = await conn.fetchrow( + "SELECT * FROM messages WHERE id = $1", message_id + ) + + if not message or message["author_id"] != author_id: + return None + + # Update (with time limit: can only edit messages < 1 hour old) + if message["created_at"] < datetime.now(timezone.utc) - timedelta(hours=1): + return None + + updated = await conn.fetchrow( + """UPDATE messages + SET content = $1, edited_at = NOW() + WHERE id = $2 + RETURNING *""", + new_content, message_id + ) + + # Broadcast update + await self.ws_manager.broadcast_to_channel( + message["channel_id"], + { + "type": "MESSAGE_UPDATE", + "data": { + "id": str(updated["id"]), + "content": updated["content"], + "edited_at": updated["edited_at"].isoformat() + } + } + ) + + return {"id": str(updated["id"])} + + async def delete_message( + self, + message_id: int, + user_id: int + ) -> bool: + """Delete a message.""" + async with self.db.acquire() as conn: + # Get message and check permissions + message = await conn.fetchrow( + """SELECT m.*, s.owner_id + FROM messages m + LEFT JOIN channels c ON m.channel_id = c.id + LEFT JOIN servers s ON c.server_id = s.id + WHERE m.id = $1""", + message_id + ) + + if not message: + return False + + # Can delete if author or server owner + if message["author_id"] != user_id and message["owner_id"] != user_id: + return False + + # Soft delete (or hard delete) + await conn.execute("DELETE FROM messages WHERE id = $1", message_id) + + # Broadcast deletion + await self.ws_manager.broadcast_to_channel( + message["channel_id"], + { + "type": "MESSAGE_DELETE", + "data": {"id": str(message_id)} + } + ) + + return True +``` + +**Integration with WebSocket manager**: +```python +# In WebSocketManager._handle_chat_message +async def _handle_chat_message(self, connection_id: str, data: dict): + await message_handler.handle_incoming_message(connection_id, data) +``` + +## Acceptance Criteria + +- [ ] Messages persisted to database +- [ ] Messages broadcast to all channel subscribers +- [ ] Message ordering preserved per channel +- [ ] Edit and delete work correctly +- [ ] Slowmode restriction enforced +- [ ] Permission checks prevent unauthorized messages +- [ ] Non-author users cannot edit/delete messages + +## Notes + +**Trade-offs**: +- Queue vs direct broadcast: Queue smooths bursts, adds latency +- Soft delete vs hard delete: Hard delete for privacy + +**Performance**: +- Message queue prevents blocking on slow broadcasts +- Channel position maintains ordering without locks + +**Alternatives considered**: +- Event sourcing: Rejected, too complex for MVP +- Message broker (Kafka): Rejected, adds infrastructure diff --git a/ai_coder_1/subtasks/Decomp-002-04.md b/ai_coder_1/subtasks/Decomp-002-04.md new file mode 100644 index 0000000..306824a --- /dev/null +++ b/ai_coder_1/subtasks/Decomp-002-04.md @@ -0,0 +1,376 @@ +# Subtask: Message History and Pagination + +**Parent Task**: Decomp/002 +**Subtask ID**: Decomp/002-04 +**Dependencies**: Decomp/002-01 (Database Schema), Decomp/002-03 (Message Delivery) + +## Description + +Implement efficient message history retrieval with pagination. Support cursor-based pagination for performance, around-cursor fetching, and filtering options. + +## Requirements + +- Paginated message history per channel +- Cursor-based pagination (not offset-based) +- Fetch messages before/after a cursor +- Limit message count per request (max 100) +- Include message reactions in response +- Support filtering by author, date range +- Efficient queries at scale (billions of messages) + +## Technical Specifications + +**Cursor format**: Base64-encoded JSON with message_id and timestamp + +```python +import base64 +import json +from typing import List, Optional, Dict, Any + +def encode_cursor(message_id: int, created_at: datetime) -> str: + """Encode cursor from message data.""" + data = { + "id": message_id, + "ts": created_at.isoformat() + } + return base64.urlsafe_b64encode(json.dumps(data).encode()).decode() + +def decode_cursor(cursor: str) -> Dict[str, Any]: + """Decode cursor to message data.""" + data = json.loads(base64.urlsafe_b64decode(cursor)) + return { + "id": int(data["id"]), + "ts": datetime.fromisoformat(data["ts"]) + } + +class MessageHistoryHandler: + """Handle message history queries.""" + + def __init__(self, db_pool): + self.db = db_pool + self.max_limit = 100 + self.default_limit = 50 + + async def get_messages( + self, + channel_id: int, + limit: int = None, + before: str = None, + after: str = None, + around: str = None, + author_id: int = None, + include_reactions: bool = True + ) -> Dict[str, Any]: + """ + Fetch messages with pagination. + + Args: + channel_id: Channel to fetch from + limit: Max messages to return (default: 50, max: 100) + before: Cursor - fetch messages before this point + after: Cursor - fetch messages after this point + around: Cursor - fetch messages around this point (50/50 split) + author_id: Filter by author + include_reactions: Include reaction data + + Returns: + { + "messages": [...], + "has_more_before": bool, + "has_more_after": bool, + "next_cursor": str or None, + "prev_cursor": str or None + } + """ + limit = min(limit or self.default_limit, self.max_limit) + + if around: + return await self._get_around(channel_id, around, limit, author_id, include_reactions) + elif before: + return await self._get_before(channel_id, before, limit, author_id, include_reactions) + elif after: + return await self._get_after(channel_id, after, limit, author_id, include_reactions) + else: + return await self._get_latest(channel_id, limit, author_id, include_reactions) + + async def _get_latest( + self, + channel_id: int, + limit: int, + author_id: Optional[int], + include_reactions: bool + ) -> Dict[str, Any]: + """Get latest messages from channel.""" + async with self.db.acquire() as conn: + # Build query + author_filter = "AND author_id = $3" if author_id else "" + params = [channel_id, limit] + if author_id: + params.append(author_id) + + query = f""" + SELECT + m.*, + u.username, u.display_name, u.avatar_url, + r.reactions + FROM messages m + JOIN users u ON m.author_id = u.id + LEFT JOIN LATERAL ( + SELECT json_agg(json_build_object( + 'emoji', mr.emoji, + 'emoji_type', mr.emoji_type, + 'count', COUNT(*) + )) as reactions + FROM message_reactions mr + WHERE mr.message_id = m.id + GROUP BY mr.message_id + ) r ON true + WHERE m.channel_id = $1 + {author_filter} + ORDER BY m.channel_position DESC + LIMIT $2 + """ + + rows = await conn.fetch(query, *params) + messages = [self._format_message(row) for row in rows] + messages.reverse() # Return in chronological order + + return { + "messages": messages, + "has_more_before": False, + "has_more_after": len(messages) == limit, + "next_cursor": encode_cursor(messages[0]["id"], messages[0]["created_at"]) if messages else None, + "prev_cursor": None + } + + async def _get_before( + self, + channel_id: int, + cursor: str, + limit: int, + author_id: Optional[int], + include_reactions: bool + ) -> Dict[str, Any]: + """Get messages before the cursor (older messages).""" + cursor_data = decode_cursor(cursor) + + async with self.db.acquire() as conn: + author_filter = "AND m.author_id = $4" if author_id else "" + params = [channel_id, cursor_data["id"], limit] + if author_id: + params.append(author_id) + + query = f""" + SELECT + m.*, + u.username, u.display_name, u.avatar_url, + r.reactions + FROM messages m + JOIN users u ON m.author_id = u.id + LEFT JOIN LATERAL ( + SELECT json_agg(json_build_object( + 'emoji', mr.emoji, + 'emoji_type', mr.emoji_type, + 'count', COUNT(*) + )) as reactions + FROM message_reactions mr + WHERE mr.message_id = m.id + GROUP BY mr.message_id + ) r ON true + WHERE m.channel_id = $1 + AND m.id < $2 + {author_filter} + ORDER BY m.channel_position DESC + LIMIT $3 + """ + + rows = await conn.fetch(query, *params) + messages = [self._format_message(row) for row in rows] + messages.reverse() + + return { + "messages": messages, + "has_more_before": len(messages) == limit, + "has_more_after": True, + "next_cursor": encode_cursor(messages[0]["id"], messages[0]["created_at"]) if messages else None, + "prev_cursor": encode_cursor(messages[-1]["id"], messages[-1]["created_at"]) if messages else None + } + + async def _get_after( + self, + channel_id: int, + cursor: str, + limit: int, + author_id: Optional[int], + include_reactions: bool + ) -> Dict[str, Any]: + """Get messages after the cursor (newer messages).""" + cursor_data = decode_cursor(cursor) + + async with self.db.acquire() as conn: + author_filter = "AND m.author_id = $4" if author_id else "" + params = [channel_id, cursor_data["id"], limit] + if author_id: + params.append(author_id) + + query = f""" + SELECT + m.*, + u.username, u.display_name, u.avatar_url, + r.reactions + FROM messages m + JOIN users u ON m.author_id = u.id + LEFT JOIN LATERAL ( + SELECT json_agg(json_build_object( + 'emoji', mr.emoji, + 'emoji_type', mr.emoji_type, + 'count', COUNT(*) + )) as reactions + FROM message_reactions mr + WHERE mr.message_id = m.id + GROUP BY mr.message_id + ) r ON true + WHERE m.channel_id = $1 + AND m.id > $2 + {author_filter} + ORDER BY m.channel_position ASC + LIMIT $3 + """ + + rows = await conn.fetch(query, *params) + messages = [self._format_message(row) for row in rows] + + return { + "messages": messages, + "has_more_before": True, + "has_more_after": len(messages) == limit, + "next_cursor": encode_cursor(messages[-1]["id"], messages[-1]["created_at"]) if messages else None, + "prev_cursor": encode_cursor(messages[0]["id"], messages[0]["created_at"]) if messages else None + } + + async def _get_around( + self, + channel_id: int, + cursor: str, + limit: int, + author_id: Optional[int], + include_reactions: bool + ) -> Dict[str, Any]: + """Get messages around the cursor (half before, half after).""" + cursor_data = decode_cursor(cursor) + half_limit = limit // 2 + + async with self.db.acquire() as conn: + # Get messages before + author_filter = "AND author_id = $4" if author_id else "" + params_before = [channel_id, cursor_data["id"], half_limit] + if author_id: + params_before.append(author_id) + + query_before = f""" + SELECT m.*, u.username, u.display_name, u.avatar_url + FROM messages m + JOIN users u ON m.author_id = u.id + WHERE m.channel_id = $1 AND m.id < $2 {author_filter} + ORDER BY m.channel_position DESC + LIMIT $3 + """ + rows_before = await conn.fetch(query_before, *params_before) + before_messages = [self._format_message(row) for row in reversed(rows_before)] + + # Get messages after (including cursor message) + params_after = [channel_id, cursor_data["id"], half_limit + 1] + if author_id: + params_after.append(author_id) + + query_after = f""" + SELECT m.*, u.username, u.display_name, u.avatar_url + FROM messages m + JOIN users u ON m.author_id = u.id + WHERE m.channel_id = $1 AND m.id >= $2 {author_filter} + ORDER BY m.channel_position ASC + LIMIT $3 + """ + rows_after = await conn.fetch(query_after, *params_after) + after_messages = [self._format_message(row) for row in rows_after] + + messages = before_messages + after_messages + + return { + "messages": messages, + "has_more_before": len(before_messages) == half_limit, + "has_more_after": len(after_messages) > half_limit, + "next_cursor": encode_cursor(messages[0]["id"], messages[0]["created_at"]) if messages else None, + "prev_cursor": encode_cursor(messages[-1]["id"], messages[-1]["created_at"]) if messages else None + } + + def _format_message(self, row) -> Dict[str, Any]: + """Format database row into API response.""" + return { + "id": str(row["id"]), + "channel_id": str(row["channel_id"]), + "author": { + "id": str(row["author_id"]), + "username": row["username"], + "display_name": row["display_name"], + "avatar_url": row["avatar_url"] + }, + "content": row["content"], + "type": row["type"], + "reply_to_id": str(row["reply_to_id"]) if row["reply_to_id"] else None, + "created_at": row["created_at"].isoformat(), + "edited_at": row["edited_at"].isoformat() if row["edited_at"] else None, + "channel_position": row["channel_position"], + "reactions": row.get("reactions", []) + } +``` + +**HTTP API endpoint**: +```python +from fastapi import Query + +@app.get("/api/v1/channels/{channel_id}/messages") +async def get_channel_messages( + channel_id: int, + limit: int = Query(50, le=100), + before: Optional[str] = None, + after: Optional[str] = None, + around: Optional[str] = None, + author_id: Optional[int] = None +): + """Get message history for a channel.""" + handler = MessageHistoryHandler(db_pool) + result = await handler.get_messages( + channel_id=channel_id, + limit=limit, + before=before, + after=after, + around=around, + author_id=author_id + ) + return result +``` + +## Acceptance Criteria + +- [ ] Latest messages returned correctly +- [ ] Pagination works with before/after cursors +- [ ] Around cursor returns messages on both sides +- [ ] Author filter works correctly +- [ ] Reactions included in response +- [ ] Limit enforced (max 100) +- [ ] Queries use indexes (explain analyze confirms) + +## Notes + +**Trade-offs**: +- Cursor vs offset: Cursor eliminates O(N) offset cost +- Reactions join: LATERAL join efficient for reaction counts + +**Performance**: +- Index on (channel_id, channel_position) enables efficient pagination +- Partition by month prevents full table scans + +**Alternatives considered**: +- OFFSET/LIMIT: Rejected, gets slower with larger offsets +- Materialized cache: Rejected, cache invalidation complexity diff --git a/ai_coder_1/subtasks/Decomp-002-05.md b/ai_coder_1/subtasks/Decomp-002-05.md new file mode 100644 index 0000000..d339bf4 --- /dev/null +++ b/ai_coder_1/subtasks/Decomp-002-05.md @@ -0,0 +1,366 @@ +# Subtask: Message Reactions System + +**Parent Task**: Decomp/002 +**Subtask ID**: Decomp/002-05 +**Dependencies**: Decomp/002-01 (Database Schema), Decomp/002-02 (WebSocket Manager) + +## Description + +Implement message reactions with support for both unicode emojis and custom emojis. Handle adding, removing reactions, and broadcasting reaction events. Support multiple reactions per user per message. + +## Requirements + +- Add reaction to message +- Remove reaction from message +- Custom emoji support +- Multiple reactions per user per message +- Broadcast reaction events to channel +- Prevent duplicate reactions +- Show reaction counts + +## Technical Specifications + +**Reaction handler**: +```python +from typing import Optional, List +from dataclasses import dataclass + +@dataclass +class ReactionEvent: + """A reaction add/remove event.""" + message_id: int + user_id: int + emoji: str + emoji_type: str # 'unicode' or 'custom' + event_type: str # 'add' or 'remove' + +class ReactionHandler: + """Handle message reactions.""" + + def __init__(self, ws_manager: WebSocketManager, db_pool): + self.ws_manager = ws_manager + self.db = db_pool + + async def add_reaction( + self, + message_id: int, + user_id: int, + emoji: str, + emoji_type: str = "unicode" + ) -> Optional[dict]: + """ + Add a reaction to a message. + + Returns reaction data if successful, None if failed. + """ + # Validate emoji + if emoji_type == "unicode": + if not self._is_valid_emoji(emoji): + return None + elif emoji_type == "custom": + # Check if custom emoji exists + if not await self._custom_emoji_exists(emoji): + return None + + async with self.db.acquire() as conn: + # Check if message exists + message = await conn.fetchrow( + "SELECT channel_id FROM messages WHERE id = $1", + message_id + ) + if not message: + return None + + channel_id = message["channel_id"] + + # Check for duplicate reaction + existing = await conn.fetchrow( + """SELECT id FROM message_reactions + WHERE message_id = $1 AND user_id = $2 AND emoji = $3""", + message_id, user_id, emoji + ) + if existing: + # Already reacted, return existing + return await self._get_reaction_data(message_id, emoji) + + # Add reaction + await conn.execute( + """INSERT INTO message_reactions + (message_id, user_id, emoji, emoji_type) + VALUES ($1, $2, $3, $4)""", + message_id, user_id, emoji, emoji_type + ) + + # Get reaction data with count + reaction_data = await self._get_reaction_data(message_id, emoji) + + # Broadcast to channel + await self.ws_manager.broadcast_to_channel( + channel_id, + { + "type": "MESSAGE_REACTION_ADD", + "data": { + "message_id": str(message_id), + "user_id": str(user_id), + **reaction_data + } + } + ) + + return reaction_data + + async def remove_reaction( + self, + message_id: int, + user_id: int, + emoji: str + ) -> bool: + """ + Remove a reaction from a message. + + Returns True if removed, False if not found. + """ + async with self.db.acquire() as conn: + # Get channel_id for broadcasting + message = await conn.fetchrow( + "SELECT channel_id FROM messages WHERE id = $1", + message_id + ) + if not message: + return False + + channel_id = message["channel_id"] + + # Remove reaction + result = await conn.execute( + """DELETE FROM message_reactions + WHERE message_id = $1 AND user_id = $2 AND emoji = $3""", + message_id, user_id, emoji + ) + + if result == "DELETE 0": + return False + + # Get remaining count + count = await conn.fetchval( + """SELECT COUNT(*) FROM message_reactions + WHERE message_id = $1 AND emoji = $2""", + message_id, emoji + ) + + # Broadcast removal + await self.ws_manager.broadcast_to_channel( + channel_id, + { + "type": "MESSAGE_REACTION_REMOVE", + "data": { + "message_id": str(message_id), + "user_id": str(user_id), + "emoji": emoji, + "count": count + } + } + ) + + return True + + async def get_reactions(self, message_id: int) -> List[dict]: + """Get all reactions for a message.""" + async with self.db.acquire() as conn: + rows = await conn.fetch( + """SELECT + emoji, + emoji_type, + COUNT(*) as count, + array_agg(user_id) as user_ids + FROM message_reactions + WHERE message_id = $1 + GROUP BY emoji, emoji_type + ORDER BY count DESC, emoji""", + message_id + ) + + return [ + { + "emoji": row["emoji"], + "emoji_type": row["emoji_type"], + "count": row["count"], + "user_ids": [str(uid) for uid in row["user_ids"]] + } + for row in rows + ] + + async def clear_reactions( + self, + message_id: int, + emoji: Optional[str] = None + ) -> bool: + """ + Clear reactions from a message. + If emoji specified, only clear that emoji. + Otherwise clear all reactions. + """ + async with self.db.acquire() as conn: + # Get channel_id + message = await conn.fetchrow( + "SELECT channel_id FROM messages WHERE id = $1", + message_id + ) + if not message: + return False + + channel_id = message["channel_id"] + + if emoji: + await conn.execute( + """DELETE FROM message_reactions + WHERE message_id = $1 AND emoji = $2""", + message_id, emoji + ) + else: + await conn.execute( + "DELETE FROM message_reactions WHERE message_id = $1", + message_id + ) + + # Broadcast clear event + await self.ws_manager.broadcast_to_channel( + channel_id, + { + "type": "MESSAGE_REACTION_REMOVE_ALL", + "data": { + "message_id": str(message_id), + "emoji": emoji + } + } + ) + + return True + + async def _get_reaction_data(self, message_id: int, emoji: str) -> dict: + """Get reaction data with count.""" + async with self.db.acquire() as conn: + row = await conn.fetchrow( + """SELECT + emoji, + emoji_type, + COUNT(*) as count + FROM message_reactions + WHERE message_id = $1 AND emoji = $2 + GROUP BY emoji, emoji_type""", + message_id, emoji + ) + + if not row: + return {} + + return { + "emoji": row["emoji"], + "emoji_type": row["emoji_type"], + "count": row["count"] + } + + def _is_valid_emoji(self, emoji: str) -> bool: + """Validate unicode emoji.""" + import emoji as emoji_lib + return emoji_lib.is_emoji(emoji) + + async def _custom_emoji_exists(self, emoji_id: str) -> bool: + """Check if custom emoji exists in server.""" + # Implementation depends on custom emoji storage + return True +``` + +**WebSocket message format**: +```javascript +// Add reaction +{ + "type": "REACTION_ADD", + "message_id": "123456789", + "emoji": "👍", + "emoji_type": "unicode" +} + +// Remove reaction +{ + "type": "REACTION_REMOVE", + "message_id": "123456789", + "emoji": "👍" +} +``` + +**HTTP API endpoints**: +```python +from fastapi import HTTPException + +@app.put("/api/v1/messages/{message_id}/reactions") +async def add_reaction( + message_id: int, + emoji: str, + emoji_type: str = "unicode", + current_user: User = Depends(get_current_user) +): + """Add reaction to message.""" + handler = ReactionHandler(ws_manager, db_pool) + result = await handler.add_reaction(message_id, current_user.id, emoji, emoji_type) + if not result: + raise HTTPException(status_code=400, detail="Could not add reaction") + return result + +@app.delete("/api/v1/messages/{message_id}/reactions/{emoji}") +async def remove_reaction( + message_id: int, + emoji: str, + current_user: User = Depends(get_current_user) +): + """Remove reaction from message.""" + handler = ReactionHandler(ws_manager, db_pool) + success = await handler.remove_reaction(message_id, current_user.id, emoji) + if not success: + raise HTTPException(status_code=404, detail="Reaction not found") + return {"success": True} + +@app.get("/api/v1/messages/{message_id}/reactions") +async def get_reactions(message_id: int): + """Get all reactions for a message.""" + handler = ReactionHandler(ws_manager, db_pool) + return await handler.get_reactions(message_id) + +@app.delete("/api/v1/messages/{message_id}/reactions") +async def clear_reactions( + message_id: int, + emoji: Optional[str] = None, + current_user: User = Depends(get_current_user) +): + """Clear reactions from message (admin only or message author).""" + handler = ReactionHandler(ws_manager, db_pool) + # Add permission check + success = await handler.clear_reactions(message_id, emoji) + if not success: + raise HTTPException(status_code=404, detail="Message not found") + return {"success": True} +``` + +## Acceptance Criteria + +- [ ] User can add reaction to message +- [ ] User can remove their reaction +- [ ] Duplicate reactions prevented +- [ ] Reaction count updates correctly +- [ ] Reaction events broadcast to channel +- [ ] Unicode emoji validation works +- [ ] Custom emoji support functional + +## Notes + +**Trade-offs**: +- Multiple same emoji per user: Prevented via unique constraint +- Reaction storage: Separate table allows unlimited reactions per message + +**Performance**: +- Index on (message_id, emoji, user_id) for fast lookups +- Count queries grouped by emoji for efficient aggregation + +**Alternatives considered**: +- Embedded reactions in message JSONB: Rejected, harder to query and aggregate +- Single reaction per user: Rejected, users may want to react multiple times with different emojis diff --git a/ai_coder_1/subtasks/Decomp-002-06.md b/ai_coder_1/subtasks/Decomp-002-06.md new file mode 100644 index 0000000..77ea9ae --- /dev/null +++ b/ai_coder_1/subtasks/Decomp-002-06.md @@ -0,0 +1,370 @@ +# Subtask: User Presence System + +**Parent Task**: Decomp/002 +**Subtask ID**: Decomp/002-06 +**Dependencies**: Decomp/002-01 (Database Schema), Decomp/002-02 (WebSocket Manager) + +## Description + +Implement real-time user presence tracking showing online/idle/dnd/offline status. Handle status updates, activity tracking (playing X, listening to Y), and broadcast presence changes to friends/guild members. + +## Requirements + +- Track user online/offline status +- Support idle, dnd (do not disturb), invisible statuses +- Activity display (playing game, listening to music) +- Broadcast presence to relevant users +- Handle multiple devices per user +- Presence should reflect last activity across all devices +- "Last seen" timestamp for offline users + +## Technical Specifications + +**Presence handler**: +```python +from datetime import datetime, timezone, timedelta +from enum import Enum +from typing import Optional, Dict, Set, List +import asyncio +import json + +class PresenceStatus(str, Enum): + ONLINE = "online" + IDLE = "idle" + DND = "dnd" + OFFLINE = "offline" + INVISIBLE = "invisible" + +class PresenceHandler: + """ + Handle user presence tracking and broadcasting. + + Presence is determined by: + 1. WebSocket connection state (online/offline) + 2. Last activity timestamp (idle) + 3. User-set status (dnd, invisible) + """ + + # Idle thresholds + IDLE_THRESHOLD = timedelta(minutes=5) # 5 minutes of inactivity = idle + OFFLINE_THRESHOLD = timedelta(minutes=10) # 10 minutes = offline + + def __init__(self, ws_manager: WebSocketManager, db_pool): + self.ws_manager = ws_manager + self.db = db_pool + self._cleanup_task: Optional[asyncio.Task] = None + + async def start(self): + """Start presence cleanup task.""" + self._cleanup_task = asyncio.create_task(self._cleanup_loop()) + + async def update_presence( + self, + user_id: int, + status: Optional[PresenceStatus] = None, + activities: Optional[List[dict]] = None, + connection_id: Optional[str] = None + ): + """ + Update user presence and broadcast to relevant users. + + Args: + user_id: User to update + status: New status (None = auto-detect) + activities: List of activities (games, music) + connection_id: Connection triggering update + """ + current_time = datetime.now(timezone.utc) + + # Get current user state + async with self.db.acquire() as conn: + presence_row = await conn.fetchrow( + "SELECT * FROM user_presence WHERE user_id = $1", + user_id + ) + + current_status = PresenceStatus.OFFLINE + current_activities = [] + + if presence_row: + current_status = PresenceStatus(presence_row["status"]) + current_activities = presence_row.get("activities", []) + + # Determine new status + if status: + new_status = status + else: + # Auto-detect based on connections + user_conns = self.ws_manager.user_connections.get(user_id, set()) + if user_conns: + # User has connections, check last activity + latest_activity = None + for conn_id in user_conns: + if conn_id in self.ws_manager.connections: + conn = self.ws_manager.connections[conn_id] + if latest_activity is None or conn.last_ping > latest_activity: + latest_activity = conn.last_ping + + if latest_activity: + time_since = current_time - latest_activity + if time_since > self.OFFLINE_THRESHOLD: + new_status = PresenceStatus.OFFLINE + elif time_since > self.IDLE_THRESHOLD: + new_status = PresenceStatus.IDLE + else: + new_status = PresenceStatus.ONLINE + else: + new_status = PresenceStatus.ONLINE + else: + new_status = PresenceStatus.OFFLINE + + # Invisible users appear offline to others + display_status = PresenceStatus.OFFLINE if new_status == PresenceStatus.INVISIBLE else new_status + new_activities = activities or current_activities + + # Update database + await conn.execute( + """INSERT INTO user_presence (user_id, status, last_updated, activities) + VALUES ($1, $2, $3, $4) + ON CONFLICT (user_id) DO UPDATE + SET status = $2, last_updated = $3, activities = $4""", + user_id, new_status.value, current_time, json.dumps(new_activities) + ) + + # Also update users.last_seen_at + await conn.execute( + "UPDATE users SET last_seen_at = $1 WHERE id = $2", + current_time, user_id + ) + + # Broadcast to relevant users + await self._broadcast_presence_change( + user_id, + display_status, + new_activities + ) + + async def get_presence(self, user_ids: List[int]) -> Dict[int, dict]: + """ + Get presence status for multiple users. + + Returns: + {user_id: {status, activities, last_seen}} + """ + if not user_ids: + return {} + + async with self.db.acquire() as conn: + rows = await conn.fetch( + """SELECT up.user_id, up.status, up.activities, up.last_updated, + u.last_seen_at + FROM user_presence up + JOIN users u ON up.user_id = u.id + WHERE up.user_id = ANY($1)""", + user_ids + ) + + result = {} + for row in rows: + status = PresenceStatus(row["status"]) + # Handle invisible - show as offline + display_status = PresenceStatus.OFFLINE if status == PresenceStatus.INVISIBLE else status + + result[row["user_id"]] = { + "status": display_status.value, + "activities": row.get("activities", []), + "last_seen": row["last_seen_at"].isoformat() if row["last_seen_at"] else None + } + + # Fill in offline users not in presence table + for uid in user_ids: + if uid not in result: + result[uid] = { + "status": PresenceStatus.OFFLINE.value, + "activities": [], + "last_seen": None + } + + return result + + async def set_status( + self, + user_id: int, + status: PresenceStatus, + activities: Optional[List[dict]] = None + ): + """ + Manually set user status. + + Activities format: + [ + {"type": "playing", "name": "Game Name"}, + {"type": "listening", "name": "Song Name"}, + {"type": "watching", "name": "Show Name"} + ] + """ + await self.update_presence( + user_id=user_id, + status=status, + activities=activities + ) + + async def _broadcast_presence_change( + self, + user_id: int, + status: PresenceStatus, + activities: List[dict] + ): + """ + Broadcast presence change to users who should see it. + + Relevant users: + - Users in same servers + - Users in DM channels + """ + # Get user's servers and DM partners + async with self.db.acquire() as conn: + # Get server members who should see this + server_member_ids = await conn.fetch( + """SELECT DISTINCT sm.user_id + FROM server_members sm + JOIN servers s ON sm.server_id = s.id + WHERE sm.server_id IN ( + SELECT server_id FROM server_members WHERE user_id = $1 + ) + AND sm.user_id != $1""", + user_id + ) + + # Get DM partners + dm_partner_ids = await conn.fetch( + """SELECT DISTINCT dcm.user_id + FROM dm_channel_members dcm + WHERE dcm.channel_id IN ( + SELECT channel_id FROM dm_channel_members WHERE user_id = $1 + ) + AND dcm.user_id != $1""", + user_id + ) + + # Combine and deduplicate + target_ids = set(r["user_id"] for r in server_member_ids) | set(r["user_id"] for r in dm_partner_ids) + + # Send to all online users in target set + presence_data = { + "type": "PRESENCE_UPDATE", + "data": { + "user_id": str(user_id), + "status": status.value, + "activities": activities + } + } + + for target_id in target_ids: + await self.ws_manager.send_to_user(target_id, presence_data) + + async def _cleanup_loop(self): + """Periodic cleanup of stale presence data.""" + while True: + try: + await self._cleanup_stale_presence() + await asyncio.sleep(60) # Run every minute + except Exception as e: + logger.error(f"Error in presence cleanup: {e}") + + async def _cleanup_stale_presence(self): + """Mark inactive users as offline.""" + cutoff_time = datetime.now(timezone.utc) - self.OFFLINE_THRESHOLD + + async with self.db.acquire() as conn: + # Find users who should be offline but aren't + await conn.execute( + """UPDATE user_presence + SET status = 'offline' + WHERE status IN ('online', 'idle', 'dnd') + AND last_updated < $1""", + cutoff_time + ) +``` + +**WebSocket message format**: +```javascript +// Client requests to set status +{ + "type": "PRESENCE_UPDATE", + "status": "dnd", + "activities": [ + {"type": "playing", "name": "Game Name"} + ] +} + +// Server broadcasts presence updates +{ + "type": "PRESENCE_UPDATE", + "data": { + "user_id": "123", + "status": "online", + "activities": [] + } +} +``` + +**Integration with WebSocket manager**: +```python +# When user connects +await presence_handler.update_presence(user_id, PresenceStatus.ONLINE) + +# When user disconnects (check for remaining connections) +await presence_handler.update_presence(user_id) + +# Periodic activity updates (on user interaction) +async def on_user_activity(connection_id: str): + state = ws_manager.connections[connection_id] + state.last_ping = datetime.now(timezone.utc) + await presence_handler.update_presence(state.user_id) +``` + +**HTTP API**: +```python +@app.get("/api/v1/users/{user_id}/presence") +async def get_user_presence(user_id: int): + """Get presence status for a user.""" + handler = PresenceHandler(ws_manager, db_pool) + result = await handler.get_presence([user_id]) + return result.get(user_id, {"status": "offline"}) + +@app.post("/api/v1/users/@me/presence") +async def set_my_presence( + status: PresenceStatus, + activities: Optional[List[dict]] = None, + current_user: User = Depends(get_current_user) +): + """Set my presence status.""" + handler = PresenceHandler(ws_manager, db_pool) + await handler.set_status(current_user.id, status, activities) + return {"success": True} +``` + +## Acceptance Criteria + +- [ ] User appears online when connected +- [ ] User goes idle after 5 minutes of inactivity +- [ ] User goes offline after 10 minutes or disconnect +- [ ] Presence changes broadcast to server members +- [ ] DND status prevents notifications +- [ ] Invisible status shows user as offline to others +- [ ] Activities display correctly + +## Notes + +**Trade-offs**: +- Idle timeout: 5 minutes balances responsiveness and accuracy +- Separate presence table vs users column: Separate table for efficiency + +**Performance**: +- Presence queries batched for efficiency +- Only broadcast to online users + +**Alternatives considered**: +- Redis-only presence: Rejected, want persistence +- Presence per server: Rejected, global presence simpler diff --git a/ai_coder_1/subtasks/Decomp-002-07.md b/ai_coder_1/subtasks/Decomp-002-07.md new file mode 100644 index 0000000..8c7d822 --- /dev/null +++ b/ai_coder_1/subtasks/Decomp-002-07.md @@ -0,0 +1,362 @@ +# Subtask: File Upload and Attachments + +**Parent Task**: Decomp/002 +**Subtask ID**: Decomp/002-07 +**Dependencies**: Decomp/002-01 (Database Schema), Decomp/002-03 (Message Delivery) + +## Description + +Implement file upload functionality supporting images, videos, audio, and documents. Store files efficiently, generate thumbnails for images, and attach files to messages. + +## Requirements + +- Upload files via HTTP multipart/form-data +- Support images (PNG, JPG, GIF, WebP) +- Support videos (MP4, WebM) +- Support audio (MP3, OGG, WAV) +- Support documents (PDF, TXT, etc.) +- Generate thumbnails for images +- Store file metadata in database +- Return file URL for attaching to messages +- File size limits (8MB for regular, 50MB for Nitro) +- Virus scanning (optional) + +## Technical Specifications + +**Storage backend**: S3-compatible (or local filesystem for development) + +**File upload handler**: +```python +import os +import uuid +import hashlib +from typing import Optional, Tuple +from fastapi import UploadFile, File, HTTPException +from PIL import Image +import io + +class FileUploadHandler: + """Handle file uploads and storage.""" + + # Size limits + MAX_FILE_SIZE = 8 * 1024 * 1024 # 8MB + MAX_NITRO_FILE_SIZE = 50 * 1024 * 1024 # 50MB + MAX_IMAGE_DIMENSION = 4096 + + # Allowed content types + ALLOWED_IMAGES = ["image/png", "image/jpeg", "image/gif", "image/webp"] + ALLOWED_VIDEOS = ["video/mp4", "video/webm", "video/quicktime"] + ALLOWED_AUDIO = ["audio/mpeg", "audio/ogg", "audio/wav"] + ALLOWED_DOCUMENTS = ["application/pdf", "text/plain"] + + def __init__(self, storage_backend, db_pool): + self.storage = storage_backend + self.db = db_pool + + async def upload_file( + self, + file: UploadFile, + user_id: int, + is_nitro: bool = False + ) -> dict: + """ + Upload a file and return metadata. + + Returns: + { + "id": str, + "filename": str, + "content_type": str, + "size_bytes": int, + "url": str, + "preview_url": str or None, + "width": int or None, + "height": int or None + } + """ + # Check file size + max_size = self.MAX_NITRO_FILE_SIZE if is_nitro else self.MAX_FILE_SIZE + content = await file.read() + if len(content) > max_size: + raise HTTPException( + status_code=413, + detail=f"File too large (max {max_size // (1024*1024)}MB)" + ) + + # Validate content type + content_type = file.content_type or self._detect_content_type(content, file.filename) + if not self._is_allowed_type(content_type): + raise HTTPException(status_code=415, detail="File type not allowed") + + # Generate unique filename + file_id = uuid.uuid4() + ext = os.path.splitext(file.filename or "")[1] + storage_path = f"uploads/{user_id}/{file_id}{ext}" + + # Get file dimensions for images/videos + width, height = None, None + preview_url = None + + if content_type.startswith("image/"): + width, height, preview_path = await self._process_image( + content, storage_path, file_id + ) + if preview_path: + await self.storage.upload(preview_path, content) + preview_url = await self.storage.get_url(preview_path) + elif content_type.startswith("video/"): + width, height = await self._get_video_dimensions(content) + + # Upload file + await self.storage.upload(storage_path, content) + url = await self.storage.get_url(storage_path) + + # Save to database + async with self.db.acquire() as conn: + attachment_id = await conn.fetchval( + """INSERT INTO attachments + (message_id, filename, content_type, size_bytes, + storage_path, width, height, is_spoiler) + VALUES (NULL, $1, $2, $3, $4, $5, $6, FALSE) + RETURNING id""", + file.filename or "unknown", content_type, len(content), + storage_path, width, height + ) + + return { + "id": str(attachment_id), + "filename": file.filename, + "content_type": content_type, + "size_bytes": len(content), + "url": url, + "preview_url": preview_url, + "width": width, + "height": height + } + + async def _process_image( + self, + content: bytes, + storage_path: str, + file_id: uuid.UUID + ) -> Tuple[Optional[int], Optional[int], Optional[str]]: + """Process image: resize if needed, generate preview.""" + try: + img = Image.open(io.BytesIO(content)) + + # Get original dimensions + width, height = img.size + + # Check if resize needed + if width > self.MAX_IMAGE_DIMENSION or height > self.MAX_IMAGE_DIMENSION: + img.thumbnail((self.MAX_IMAGE_DIMENSION, self.MAX_IMAGE_DIMENSION)) + output = io.BytesIO() + img.save(output, format="PNG") + content = output.getvalue() + + # Generate thumbnail preview + preview_path = f"previews/{file_id}.png" + thumbnail = img.copy() + thumbnail.thumbnail((320, 320)) + + output = io.BytesIO() + thumbnail.save(output, format="PNG") + preview_content = output.getvalue() + + # Store preview content separately + # (In production, upload preview to storage) + + return width, height, preview_path + + except Exception as e: + logger.error(f"Error processing image: {e}") + return None, None, None + + async def _get_video_dimensions(self, content: bytes) -> Tuple[Optional[int], Optional[int]]: + """Get video dimensions using ffmpeg or similar.""" + # Implementation would use ffmpeg subprocess + return None, None + + def _detect_content_type(self, content: bytes, filename: str) -> str: + """Detect content type from file magic bytes.""" + # Simple detection using magic bytes + if content.startswith(b'\x89PNG\r\n\x1a\n'): + return "image/png" + elif content.startswith(b'\xff\xd8\xff'): + return "image/jpeg" + elif content.startswith(b'GIF87a') or content.startswith(b'GIF89a'): + return "image/gif" + elif content.startswith(b'RIFF') and b'WEBP' in content[:12]: + return "image/webp" + elif content.startswith(b'%PDF'): + return "application/pdf" + else: + # Guess from filename + ext = os.path.splitext(filename or "")[1].lower() + mime_map = { + '.png': 'image/png', + '.jpg': 'image/jpeg', + '.jpeg': 'image/jpeg', + '.gif': 'image/gif', + '.webp': 'image/webp', + '.mp4': 'video/mp4', + '.webm': 'video/webm', + '.mp3': 'audio/mpeg', + '.ogg': 'audio/ogg', + '.wav': 'audio/wav', + '.pdf': 'application/pdf', + '.txt': 'text/plain', + } + return mime_map.get(ext, 'application/octet-stream') + + def _is_allowed_type(self, content_type: str) -> bool: + """Check if content type is allowed.""" + all_allowed = ( + self.ALLOWED_IMAGES + + self.ALLOWED_VIDEOS + + self.ALLOWED_AUDIO + + self.ALLOWED_DOCUMENTS + ) + return content_type in all_allowed + + async def attach_to_message( + self, + attachment_id: int, + message_id: int + ) -> bool: + """Link an attachment to a message.""" + async with self.db.acquire() as conn: + result = await conn.execute( + "UPDATE attachments SET message_id = $1 WHERE id = $2", + message_id, attachment_id + ) + return result != "UPDATE 0" + + async def get_attachment(self, attachment_id: int) -> Optional[dict]: + """Get attachment metadata.""" + async with self.db.acquire() as conn: + row = await conn.fetchrow( + "SELECT * FROM attachments WHERE id = $1", + attachment_id + ) + if not row: + return None + + return { + "id": str(row["id"]), + "filename": row["filename"], + "content_type": row["content_type"], + "size_bytes": row["size_bytes"], + "url": await self.storage.get_url(row["storage_path"]), + "width": row["width"], + "height": row["height"], + "is_spoiler": row["is_spoiler"] + } +``` + +**HTTP API endpoint**: +```python +from fastapi import Depends + +@app.post("/api/v1attachments/upload") +async def upload_file( + file: UploadFile = File(...), + current_user: User = Depends(get_current_user) +): + """Upload a file.""" + handler = FileUploadHandler(storage_backend, db_pool) + result = await handler.upload_file( + file, + current_user.id, + is_nitro=current_user.is_nitro + ) + return result + +@app.get("/api/v1/attachments/{attachment_id}") +async def get_attachment(attachment_id: int): + """Get attachment metadata.""" + handler = FileUploadHandler(storage_backend, db_pool) + result = await handler.get_attachment(attachment_id) + if not result: + raise HTTPException(status_code=404, detail="Attachment not found") + return result +``` + +**Storage backend interface**: +```python +class StorageBackend: + """Interface for file storage (S3 or local).""" + + async def upload(self, path: str, content: bytes): + """Upload file to storage.""" + raise NotImplementedError + + async def download(self, path: str) -> bytes: + """Download file from storage.""" + raise NotImplementedError + + async def delete(self, path: str): + """Delete file from storage.""" + raise NotImplementedError + + async def get_url(self, path: str) -> str: + """Get public URL for file.""" + raise NotImplementedError + +class S3Storage(StorageBackend): + """S3-compatible storage backend.""" + + def __init__(self, bucket: str, region: str): + self.bucket = bucket + self.region = region + self.client = ... # boto3 or aiobotocore client + + async def upload(self, path: str, content: bytes): + await self.client.put_object( + Bucket=self.bucket, + Key=path, + Body=content + ) + + async def get_url(self, path: str) -> str: + return f"https://{self.bucket}.s3.{self.region}.amazonaws.com/{path}" + +class LocalStorage(StorageBackend): + """Local filesystem storage for development.""" + + def __init__(self, base_path: str): + self.base_path = base_path + + async def upload(self, path: str, content: bytes): + full_path = os.path.join(self.base_path, path) + os.makedirs(os.path.dirname(full_path), exist_ok=True) + with open(full_path, 'wb') as f: + f.write(content) + + async def get_url(self, path: str) -> str: + return f"/files/{path}" +``` + +## Acceptance Criteria + +- [ ] File upload succeeds for allowed types +- [ ] File size limit enforced +- [ ] Image thumbnails generated +- [ ] Attachment metadata stored correctly +- [ ] Attachment can be linked to message +- [ ] Invalid content types rejected +- [ ] File URL is accessible + +## Notes + +**Trade-offs**: +- S3 vs local storage: S3 for production, local for development +- Thumbnail generation: Synchronous for simplicity, can be async + +**Performance**: +- Use CDN for file delivery +- Consider lazy loading previews + +**Alternatives considered**: +- Store files in database: Rejected, bloats database +- External hosting (imgur): Rejected, want control diff --git a/ai_coder_1/subtasks/Decomp-002-08.md b/ai_coder_1/subtasks/Decomp-002-08.md new file mode 100644 index 0000000..128a1fd --- /dev/null +++ b/ai_coder_1/subtasks/Decomp-002-08.md @@ -0,0 +1,346 @@ +# Subtask: HTTP Fallback and Server-Sent Events + +**Parent Task**: Decomp/002 +**Subtask ID**: Decomp/002-08 +**Dependencies**: Decomp/002-02 (WebSocket Manager) + +## Description + +Implement HTTP fallback for clients that cannot use WebSockets. Use Server-Sent Events (SSE) for real-time updates when WebSocket is unavailable. Handle graceful degradation and reconnection. + +## Requirements + +- Detect WebSocket unavailability +- SSE endpoint for real-time message updates +- Long-polling fallback for messages +- Authentication for SSE connections +- Automatic reconnection handling +- Backward-compatible API + +## Technical Specifications + +**SSE endpoint**: +```python +import asyncio +import json +from fastapi import Request +from fastapi.responses import StreamingResponse +from typing import AsyncGenerator + +class SSEHandler: + """Handle Server-Sent Events connections.""" + + def __init__(self, ws_manager: WebSocketManager, db_pool): + self.ws_manager = ws_manager + self.db = db_pool + # user_id -> queue + self.sse_queues: Dict[int, asyncio.Queue] = {} + + async def subscribe(self, user_id: int) -> AsyncGenerator[str, None]: + """ + Subscribe to SSE updates for a user. + + Yields SSE-formatted events. + """ + if user_id not in self.sse_queues: + self.sse_queues[user_id] = asyncio.Queue(maxsize=100) + + queue = self.sse_queues[user_id] + + # Send initial connection event + yield self._format_sse({"type": "CONNECTED", "user_id": str(user_id)}) + + try: + while True: + # Wait for events (with heartbeat) + try: + event = await asyncio.wait_for(queue.get(), timeout=30) + yield self._format_sse(event) + except asyncio.TimeoutError: + # Send heartbeat + yield ":heartbeat\n\n" + + except asyncio.CancelledError: + # Client disconnected + if user_id in self.sse_queues and queue is self.sse_queues[user_id]: + del self.sse_queues[user_id] + + def _format_sse(self, data: dict) -> str: + """Format data as Server-Sent Event.""" + return f"data: {json.dumps(data)}\n\n" + + async def publish_to_user(self, user_id: int, event: dict): + """Publish event to user's SSE queue if exists.""" + if user_id in self.sse_queues: + try: + self.sse_queues[user_id].put_nowait(event) + except asyncio.QueueFull: + # Queue full, client is slow, remove oldest + try: + self.sse_queues[user_id].get_nowait() + self.sse_queues[user_id].put_nowait(event) + except: + pass + + async def broadcast_message(self, message: dict, channel_id: int): + """Broadcast message to SSE subscribers.""" + # Get users who can see this channel + async with self.db.acquire() as conn: + rows = await conn.fetch( + """SELECT DISTINCT sm.user_id + FROM server_members sm + JOIN channels c ON c.server_id = sm.server_id + WHERE c.id = $1 + UNION + SELECT user_id FROM dm_channel_members WHERE channel_id = $1""", + channel_id + ) + + for row in rows: + await self.publish_to_user(row["user_id"], { + "type": "MESSAGE_CREATE", + "data": message + }) + + async def broadcast_presence(self, user_id: int, status: str): + """Broadcast presence update to SSE subscribers.""" + # Get relevant users (same logic as WebSocket presence) + async with self.db.acquire() as conn: + rows = await conn.fetch( + """SELECT DISTINCT sm.user_id + FROM server_members sm + WHERE sm.server_id IN (SELECT server_id FROM server_members WHERE user_id = $1) + AND sm.user_id != $1""", + user_id + ) + + for row in rows: + await self.publish_to_user(row["user_id"], { + "type": "PRESENCE_UPDATE", + "data": {"user_id": str(user_id), "status": status} + }) +``` + +**SSE HTTP endpoint**: +```python +@app.get("/api/v1/sse") +async def sse_endpoint( + request: Request, + token: str +): + """ + Server-Sent Events endpoint for real-time updates. + + Use this when WebSocket is not available. + + Query params: + token: Authentication token + + Events: + - MESSAGE_CREATE: New message + - MESSAGE_UPDATE: Message edited + - MESSAGE_DELETE: Message deleted + - PRESENCE_UPDATE: User status changed + - TYPING_START: User typing + """ + # Authenticate + user_id = await authenticate_token(token) + if not user_id: + return Response("Invalid token", status_code=401) + + handler = SSEHandler(ws_manager, db_pool) + + async def event_stream(): + try: + async for event in handler.subscribe(user_id): + yield event + except asyncio.CancelledError: + pass + + return StreamingResponse( + event_stream(), + media_type="text/event-stream", + headers={ + "Cache-Control": "no-cache", + "Connection": "keep-alive", + "X-Accel-Buffering": "no" # Disable nginx buffering + } + ) +``` + +**Long-polling fallback**: +```python +@app.get("/api/v1/poll") +async def long_poll_endpoint( + request: Request, + token: str, + since: Optional[float] = None, + timeout: int = 30 +): + """ + Long-polling endpoint for message updates. + + Query params: + token: Authentication token + since: Unix timestamp of last poll + timeout: Max wait time (default 30s) + + Returns new messages since last poll or waits until new message arrives. + """ + user_id = await authenticate_token(token) + if not user_id: + return Response("Invalid token", status_code=401) + + since_time = datetime.fromtimestamp(since, timezone.utc) if since else None + + # Wait for new messages or timeout + start_time = time.time() + messages = [] + + while time.time() - start_time < timeout: + # Check for new messages + async with db_pool.acquire() as conn: + query = """ + SELECT m.*, u.username, u.display_name + FROM messages m + JOIN users u ON m.author_id = u.id + JOIN channel_members cm ON cm.channel_id = m.channel_id + WHERE cm.user_id = $1 + """ + params = [user_id] + + if since_time: + query += " AND m.created_at > $2" + params.append(since_time) + + query += " ORDER BY m.created_at ASC LIMIT 50" + + rows = await conn.fetch(query, *params) + + if rows: + messages = [dict(row) for row in rows] + break + + # Wait a bit before checking again + await asyncio.sleep(1) + + return { + "messages": messages, + "timestamp": time.time() + } +``` + +**Client-side connection manager**: +```python +class ChatClient: + """Client-side connection manager with automatic fallback.""" + + def __init__(self, token: str): + self.token = token + self.ws = None + self.sse = None + self.transport = None # 'websocket', 'sse', or 'polling' + self.reconnect_delay = 1000 # Start at 1 second + + async def connect(self): + """Try to connect, falling back as needed.""" + # Try WebSocket first + try: + await self._connect_websocket() + return + except Exception as e: + logger.info(f"WebSocket failed: {e}, trying SSE") + + # Try SSE + try: + await self._connect_sse() + return + except Exception as e: + logger.info(f"SSE failed: {e}, trying polling") + + # Fall back to polling + await self._connect_polling() + + async def _connect_websocket(self): + """Establish WebSocket connection.""" + import websockets + + self.ws = await websockets.connect( + f"ws://localhost/ws?token={self.token}" + ) + self.transport = 'websocket' + self.reconnect_delay = 1000 # Reset delay on success + + asyncio.create_task(self._listen_websocket()) + + async def _listen_websocket(self): + """Listen for WebSocket messages.""" + try: + async for message in self.ws: + data = json.loads(message) + await self._handle_event(data) + except: + await self.reconnect() + + async def _connect_sse(self): + """Establish SSE connection.""" + import aiohttp + + self.sse = aiohttp.ClientSession() + async with self.sse.get( + f"http://localhost/api/v1/sse?token={self.token}" + ) as response: + self.transport = 'sse' + async for line in response.content: + if line.startswith(b"data: "): + data = json.loads(line[6:].decode()) + await self._handle_event(data) + + async def _connect_polling(self): + """Use long-polling.""" + self.transport = 'polling' + self.last_poll = time.time() + + while True: + try: + response = await fetch( + f"/api/v1/poll?token={self.token}&since={self.last_poll}" + ) + self.last_poll = response["timestamp"] + + for msg in response["messages"]: + await self._handle_event(msg) + + except Exception as e: + logger.error(f"Polling error: {e}") + await asyncio.sleep(5) # Wait before retry + + async def reconnect(self): + """Reconnect with exponential backoff.""" + await asyncio.sleep(self.reconnect_delay / 1000) + self.reconnect_delay = min(self.reconnect_delay * 2, 30000) # Max 30s + await self.connect() +``` + +## Acceptance Criteria + +- [ ] SSE endpoint delivers real-time updates +- [ ] SSE connection authenticates correctly +- [ ] Long-polling returns new messages +- [ ] Client falls back from WebSocket to SSE to polling +- [ ] Reconnection works with exponential backoff +- [ ] Heartbeat prevents connection timeout + +## Notes + +**Trade-offs**: +- SSE vs polling: SSE more efficient but requires HTTP/2 support +- Shared event bus: SSE and WebSocket publish to same source + +**Performance**: +- SSE queues limited to 100 events per user +- Polling interval minimum 1 second + +**Alternatives considered**: +- WebRTC data channels: Rejected, too complex +- Pure HTTP polling: Rejected, too much overhead diff --git a/ai_coder_1/subtasks/Decomp-003-01.md b/ai_coder_1/subtasks/Decomp-003-01.md new file mode 100644 index 0000000..9a973d4 --- /dev/null +++ b/ai_coder_1/subtasks/Decomp-003-01.md @@ -0,0 +1,272 @@ +# Subtask: Database Schema for Task Queue + +**Parent Task**: Decomp/003 +**Subtask ID**: Decomp/003-01 +**Dependencies**: None + +## Description + +Design and implement database schema for distributed task queue supporting task scheduling, priorities, retries, result storage, and workflow dependencies. Schema must support high write throughput (1M tasks/day). + +## Requirements + +- Store tasks with metadata and arguments +- Support task priorities (high, normal, low) +- Track task status (pending, running, completed, failed) +- Store task results and error messages +- Support task dependencies (DAG execution) +- Track retry counts and backoff schedules +- Worker registration and heartbeat tracking +- Task queue partitioning by queue name + +## Technical Specifications + +**Database choice**: PostgreSQL for ACID, with Redis as broker for performance + +**Schema definition**: +```sql +-- Task queues +CREATE TABLE task_queues ( + id SERIAL PRIMARY KEY, + name VARCHAR(100) NOT NULL UNIQUE, + description TEXT, + priority INTEGER DEFAULT 5, -- Default priority for tasks in this queue + max_retries INTEGER DEFAULT 3, + retry_backoff_base INTEGER DEFAULT 2, -- Exponential backoff base + retry_backoff_max INTEGER DEFAULT 3600, -- Max backoff in seconds + created_at TIMESTAMP NOT NULL DEFAULT NOW(), + is_active BOOLEAN DEFAULT TRUE +); + +-- Tasks table +CREATE TABLE tasks ( + id BIGSERIAL PRIMARY KEY, + queue_id INTEGER NOT NULL REFERENCES task_queues(id) ON DELETE RESTRICT, + task_name VARCHAR(200) NOT NULL, -- Function name to execute + args JSONB DEFAULT '[]'::jsonb, -- Positional arguments + kwargs JSONB DEFAULT '{}'::jsonb, -- Keyword arguments + priority INTEGER DEFAULT 5, -- 0=highest, 10=lowest + status VARCHAR(20) NOT NULL DEFAULT 'pending', -- pending, running, completed, failed, cancelled + result JSONB, -- Task result (if successful) + error TEXT, -- Error message (if failed) + traceback TEXT, -- Full traceback (if failed) + retry_count INTEGER DEFAULT 0, + max_retries INTEGER DEFAULT 3, + scheduled_at TIMESTAMP, -- For scheduled/cron tasks + started_at TIMESTAMP, + completed_at TIMESTAMP, + expires_at TIMESTAMP, -- Result expiration + worker_id INTEGER, -- Worker that executed the task + parent_task_id BIGINT REFERENCES tasks(id) ON DELETE CASCADE, -- For workflow/chaining + task_group_id VARCHAR(100), -- For grouping related tasks + metadata JSONB DEFAULT '{}'::jsonb, -- Custom metadata + created_at TIMESTAMP NOT NULL DEFAULT NOW(), + updated_at TIMESTAMP NOT NULL DEFAULT NOW() +); + +-- Indexes for task processing +CREATE INDEX idx_tasks_queue_status ON tasks(queue_id, status) + WHERE status IN ('pending', 'retry'); +CREATE INDEX idx_tasks_priority ON tasks(queue_id, priority, created_at) + WHERE status IN ('pending', 'retry'); +CREATE INDEX idx_tasks_scheduled ON tasks(scheduled_at) + WHERE status = 'pending' AND scheduled_at IS NOT NULL; +CREATE INDEX idx_tasks_worker ON tasks(worker_id) + WHERE status = 'running'; +CREATE INDEX idx_tasks_parent ON tasks(parent_task_id) + WHERE status != 'completed'; +CREATE INDEX idx_tasks_group ON tasks(task_group_id); +CREATE INDEX idx_tasks_created_at ON tasks(created_at DESC); + +-- Task dependencies (DAG support) +CREATE TABLE task_dependencies ( + id BIGSERIAL PRIMARY KEY, + task_id BIGINT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE, + depends_on_task_id BIGINT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE, + UNIQUE(task_id, depends_on_task_id) +); + +CREATE INDEX idx_task_deps_task ON task_dependencies(task_id); +CREATE INDEX idx_task_deps_depends ON task_dependencies(depends_on_task_id); + +-- Workers table +CREATE TABLE workers ( + id SERIAL PRIMARY KEY, + worker_name VARCHAR(200) NOT NULL UNIQUE, + pid INTEGER, -- Process ID + hostname VARCHAR(255), + queues JSONB DEFAULT '[]'::jsonb, -- Queues this worker processes + concurrency INTEGER DEFAULT 1, -- Max concurrent tasks + current_tasks INTEGER DEFAULT 0, -- Currently running tasks + last_heartbeat TIMESTAMP NOT NULL DEFAULT NOW(), + started_at TIMESTAMP NOT NULL DEFAULT NOW(), + metadata JSONB DEFAULT '{}'::jsonb +); + +CREATE INDEX idx_workers_heartbeat ON workers(last_heartbeat); +CREATE INDEX idx_workers_active ON workers(last_heartbeat) + WHERE last_heartbeat > NOW() - INTERVAL '1 minute'; + +-- Task execution history (for analytics) +CREATE TABLE task_history ( + id BIGSERIAL PRIMARY KEY, + task_id BIGINT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE, + worker_id INTEGER REFERENCES workers(id) ON DELETE SET NULL, + status VARCHAR(20) NOT NULL, + timestamp TIMESTAMP NOT NULL DEFAULT NOW(), + details JSONB +); + +CREATE INDEX idx_task_history_task ON task_history(task_id, timestamp); +CREATE INDEX idx_task_history_timestamp ON task_history(timestamp DESC); + +-- Periodic/Cron tasks +CREATE TABLE periodic_tasks ( + id SERIAL PRIMARY KEY, + name VARCHAR(200) NOT NULL UNIQUE, + task_name VARCHAR(200) NOT NULL, + args JSONB DEFAULT '[]'::jsonb, + kwargs JSONB DEFAULT '{}'::jsonb, + queue_id INTEGER NOT NULL REFERENCES task_queues(id), + cron_expression VARCHAR(100) NOT NULL, -- Standard cron expression + last_run_at TIMESTAMP, + next_run_at TIMESTAMP, + is_active BOOLEAN DEFAULT TRUE, + metadata JSONB DEFAULT '{}'::jsonb, + created_at TIMESTAMP NOT NULL DEFAULT NOW() +); + +CREATE INDEX idx_periodic_next_run ON periodic_tasks(next_run_at) + WHERE is_active = TRUE; + +-- Locks for distributed coordination +CREATE TABLE advisory_locks ( + lock_key VARCHAR(255) PRIMARY KEY, + acquired_by VARCHAR(255) NOT NULL, + acquired_at TIMESTAMP NOT NULL DEFAULT NOW(), + expires_at TIMESTAMP NOT NULL +); + +CREATE INDEX idx_locks_expires ON advisory_locks(expires_at); + +-- Functions and triggers +CREATE OR REPLACE FUNCTION update_updated_at() +RETURNS TRIGGER AS $$ +BEGIN + NEW.updated_at = NOW(); + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER tasks_updated_at + BEFORE UPDATE ON tasks + FOR EACH ROW + EXECUTE FUNCTION update_updated_at(); + +-- Function to dequeue tasks (atomic, with FOR UPDATE SKIP LOCKED) +CREATE OR REPLACE FUNCTION dequeue_tasks( + p_queue_id INTEGER, + p_worker_id INTEGER, + p_limit INTEGER DEFAULT 1 +) +RETURNS SETOF tasks AS $$ +DECLARE + task_record tasks; +BEGIN + -- Update worker heartbeat + UPDATE workers SET last_heartbeat = NOW() WHERE id = p_worker_id; + + -- Find and lock pending tasks + FOR task_record IN + SELECT t.id + FROM tasks t + WHERE t.queue_id = p_queue_id + AND t.status = 'pending' + AND (t.scheduled_at IS NULL OR t.scheduled_at <= NOW()) + AND NOT EXISTS ( + -- Check if dependencies are satisfied + SELECT 1 FROM task_dependencies td + WHERE td.task_id = t.id + AND NOT EXISTS ( + SELECT 1 FROM tasks dep + WHERE dep.id = td.depends_on_task_id + AND dep.status = 'completed' + ) + ) + ORDER BY t.priority ASC, t.created_at ASC + LIMIT p_limit + FOR UPDATE SKIP LOCKED + LOOP + -- Mark as running + UPDATE tasks + SET status = 'running', + started_at = NOW(), + worker_id = p_worker_id + WHERE id = task_record.id; + + -- Increment worker's current task count + UPDATE workers + SET current_tasks = current_tasks + 1 + WHERE id = p_worker_id; + + RETURN QUERY SELECT * FROM tasks WHERE id = task_record.id; + END LOOP; + RETURN; +END; +$$ LANGUAGE plpgsql; +``` + +**Redis data structures for broker** (alternative/complement to SQL): +``` +# Task queue (list) +queue:{name}:pending -> [task_id1, task_id2, ...] + +# Task data (hash) +task:{task_id} -> { + "queue": "default", + "name": "task_function", + "args": "[...]", + "kwargs": "{...}", + "priority": "5", + "retry_count": "0" +} + +# Scheduled tasks (sorted set) +schedule:tasks -> {score: scheduled_time, member: task_json} + +# Running tasks (set) +workers:{worker_id}:running -> {task_id1, task_id2} + +# Task results (string with expiration) +result:{task_id} -> json_result (TTL: 1 day) + +# Worker heartbeats (hash with expiration) +worker:{worker_id}:heartbeat -> {"last_seen": timestamp} + +# Locks (for distributed operations) +lock:{name} -> worker_id (with TTL) +``` + +## Acceptance Criteria + +- [ ] All tables created without errors +- [ ] Foreign key constraints enforced +- [ ] dequeue_tasks function atomically reserves tasks +- [ ] SKIP LOCKED prevents worker contention +- [ ] Task dependencies tracked correctly +- [ ] Worker heartbeat tracking functional +- [ ] Cron tasks can be scheduled + +## Notes + +**Trade-offs**: +- PostgreSQL vs Redis broker: PostgreSQL for persistence, Redis for performance +- Skip locked vs advisory locks: Skip locked simpler for queues + +**Scalability**: +- Partition tasks table by queue_id for very high throughput +- Consider separate history database for analytics + +**Alternatives considered**: +- Redis-only: Rejected, lacks durability for requirements +- MongoDB: Rejected, weaker transaction support diff --git a/ai_coder_1/subtasks/Decomp-003-02.md b/ai_coder_1/subtasks/Decomp-003-02.md new file mode 100644 index 0000000..a2069e5 --- /dev/null +++ b/ai_coder_1/subtasks/Decomp-003-02.md @@ -0,0 +1,437 @@ +# Subtask: Task Producer API + +**Parent Task**: Decomp/003 +**Subtask ID**: Decomp/003-02 +**Dependencies**: Decomp-003-01 (Database Schema) + +## Description + +Implement task producer API for enqueueing tasks. Support both synchronous (execute now) and asynchronous (enqueue for later) execution. Handle task scheduling with priorities, delays, and cron expressions. + +## Requirements + +- Enqueue tasks for async execution +- Execute tasks synchronously and return result +- Schedule tasks for future execution +- Set task priorities +- Support task chaining (one task's result feeds into next) +- Support task groups (parallel execution) +- Task deduplication prevention +- Task cancellation + +## Technical Specifications + +**Task producer client**: +```python +import json +import uuid +from datetime import datetime, timedelta, timezone +from typing import Any, Optional, List, Union, Callable +from dataclasses import dataclass, field +from enum import Enum +import asyncio + +class TaskPriority(Enum): + HIGH = 0 + ABOVE_NORMAL = 3 + NORMAL = 5 + BELOW_NORMAL = 7 + LOW = 10 + +class TaskStatus(Enum): + PENDING = "pending" + RUNNING = "running" + COMPLETED = "completed" + FAILED = "failed" + CANCELLED = "cancelled" + RETRY = "retry" + +@dataclass +class TaskResult: + """Result of a task execution.""" + task_id: str + status: TaskStatus + result: Any = None + error: Optional[str] = None + traceback: Optional[str] = None + started_at: Optional[datetime] = None + completed_at: Optional[datetime] = None + +class TaskProducer: + """Client for enqueueing and managing tasks.""" + + def __init__(self, broker, default_queue: str = "default"): + self.broker = broker # Redis or database connection + self.default_queue = default_queue + + async def apply_async( + self, + task_func: Union[str, Callable], + args: List[Any] = None, + kwargs: dict = None, + queue: str = None, + priority: TaskPriority = TaskPriority.NORMAL, + eta: Optional[datetime] = None, + expires: Optional[datetime] = None, + retry: bool = True, + max_retries: int = 3, + task_id: str = None, + group_id: str = None, + dependencies: List[str] = None + ) -> str: + """ + Apply a task asynchronously. + + Args: + task_func: Function name or callable + args: Positional arguments + kwargs: Keyword arguments + queue: Queue name (default: self.default_queue) + priority: Task priority + eta: Earliest time to execute + expires: Task expiration time + retry: Enable retry on failure + max_retries: Maximum retry attempts + task_id: Custom task ID (auto-generated if None) + group_id: Task group ID for grouped tasks + dependencies: List of task IDs this task depends on + + Returns: + Task ID + """ + # Get task name + if callable(task_func): + task_name = f"{task_func.__module__}.{task_func.__name__}" + else: + task_name = task_func + + # Generate task ID if not provided + task_id = task_id or str(uuid.uuid4()) + + # Serialize arguments + args_data = self._serialize_args(args or []) + kwargs_data = self._serialize_args(kwargs or {}) + + # Build task data + task_data = { + "id": task_id, + "name": task_name, + "args": args_data, + "kwargs": kwargs_data, + "queue": queue or self.default_queue, + "priority": priority.value, + "retry": retry, + "max_retries": max_retries, + "retry_count": 0, + "group_id": group_id, + "created_at": datetime.now(timezone.utc).isoformat() + } + + # Add to database + await self._persist_task( + task_data=task_data, + eta=eta, + expires=expires, + dependencies=dependencies + ) + + # Add to broker queue (unless scheduled for future) + if eta is None or eta <= datetime.now(timezone.utc): + await self.broker.enqueue( + queue=queue or self.default_queue, + task_id=task_id, + priority=priority.value + ) + else: + # Schedule for later + await self.broker.schedule( + task_id=task_id, + scheduled_time=eta + ) + + return task_id + + async def apply( + self, + task_func: Union[str, Callable], + args: List[Any] = None, + kwargs: dict = None, + timeout: Optional[float] = None + ) -> TaskResult: + """ + Apply a task synchronously and wait for result. + + Executes the task inline (not through worker). + """ + # Get task name + if callable(task_func): + task_name = f"{task_func.__module__}.{task_func.__name__}" + func = task_func + else: + task_name = task_func + func = self._get_task_function(task_name) + + # Execute + start_time = datetime.now(timezone.utc) + try: + if asyncio.iscoroutinefunction(func): + result = await asyncio.wait_for( + func(*(args or []), **(kwargs or {})), + timeout=timeout + ) + else: + result = await asyncio.to_thread( + func, *(args or []), **(kwargs or {}) + ) + + return TaskResult( + task_id=str(uuid.uuid4()), + status=TaskStatus.COMPLETED, + result=result, + started_at=start_time, + completed_at=datetime.now(timezone.utc) + ) + except asyncio.TimeoutError: + return TaskResult( + task_id=str(uuid.uuid4()), + status=TaskStatus.FAILED, + error="Task timed out", + started_at=start_time, + completed_at=datetime.now(timezone.utc) + ) + except Exception as e: + return TaskResult( + task_id=str(uuid.uuid4()), + status=TaskStatus.FAILED, + error=str(e), + traceback=traceback.format_exc(), + started_at=start_time, + completed_at=datetime.now(timezone.utc) + ) + + async def chain(self, *tasks) -> str: + """ + Chain tasks: each task receives the previous task's result. + + Returns: + Chain ID (last task's ID) + """ + parent_id = None + + for task in tasks: + if parent_id: + # Set dependency on previous task + task["dependencies"] = task.get("dependencies", []) + [parent_id] + parent_id = await self.apply_async(**task) + + return parent_id + + async def group(self, *tasks) -> str: + """ + Group tasks: execute in parallel. + + Returns: + Group ID + """ + group_id = str(uuid.uuid4()) + + # Enqueue all tasks with same group_id + task_ids = [] + for task in tasks: + task["group_id"] = group_id + task_id = await self.apply_async(**task) + task_ids.append(task_id) + + return group_id + + async def chord(self, header, body) -> str: + """ + Chord: execute tasks in parallel, then callback with results. + + Args: + header: List of tasks to execute in parallel + body: Callback task (receives list of results) + + Returns: + Chord ID + """ + group_id = await self.group(*header) + + # Create a barrier task that waits for group completion + # then executes the callback + barrier_task = { + "task_func": "_chord_barrier", + "kwargs": { + "group_id": group_id, + "callback": body + } + } + + return await self.apply_async(**barrier_task) + + async def cancel(self, task_id: str) -> bool: + """Cancel a pending or running task.""" + # Update database + async with self.broker.db.acquire() as conn: + result = await conn.execute( + """UPDATE tasks + SET status = 'cancelled', completed_at = NOW() + WHERE id = $1 AND status IN ('pending', 'running')""", + task_id + ) + return result != "UPDATE 0" + + async def get_result(self, task_id: str, timeout: Optional[float] = None) -> TaskResult: + """Get task result, waiting if not ready.""" + start_time = datetime.now(timezone.utc) + + while True: + result = await self._get_task_result(task_id) + if result.status in (TaskStatus.COMPLETED, TaskStatus.FAILED, TaskStatus.CANCELLED): + return result + + if timeout and (datetime.now(timezone.utc) - start_time).total_seconds() > timeout: + raise TimeoutError(f"Task {task_id} did not complete within {timeout}s") + + await asyncio.sleep(0.5) + + async def _persist_task( + self, + task_data: dict, + eta: Optional[datetime], + expires: Optional[datetime], + dependencies: List[str] + ): + """Persist task to database.""" + async with self.broker.db.acquire() as conn: + # Get queue ID + queue_id = await conn.fetchval( + "SELECT id FROM task_queues WHERE name = $1", + task_data["queue"] + ) + + # Insert task + task_id = await conn.fetchval( + """INSERT INTO tasks + (id, queue_id, task_name, args, kwargs, priority, + scheduled_at, expires_at, max_retries, task_group_id) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) + RETURNING id""", + task_data["id"], + queue_id, + task_data["name"], + json.dumps(task_data["args"]), + json.dumps(task_data["kwargs"]), + task_data["priority"], + eta, + expires, + task_data["max_retries"], + task_data["group_id"] + ) + + # Insert dependencies + if dependencies: + for dep_id in dependencies: + await conn.execute( + "INSERT INTO task_dependencies (task_id, depends_on_task_id) VALUES ($1, $2)", + task_id, dep_id + ) + + def _serialize_args(self, args: Any) -> str: + """Serialize arguments to JSON.""" + return json.dumps(args, default=str) + + async def _get_task_result(self, task_id: str) -> TaskResult: + """Get task result from database.""" + async with self.broker.db.acquire() as conn: + row = await conn.fetchrow( + "SELECT * FROM tasks WHERE id = $1", + task_id + ) + + if not row: + raise ValueError(f"Task {task_id} not found") + + return TaskResult( + task_id=task_id, + status=TaskStatus(row["status"]), + result=row["result"], + error=row["error"], + traceback=row["traceback"], + started_at=row["started_at"], + completed_at=row["completed_at"] + ) +``` + +**Decorator for task functions**: +```python +def task( + name: str = None, + queue: str = "default", + priority: TaskPriority = TaskPriority.NORMAL, + max_retries: int = 3, + retry_backoff: bool = True +): + """ + Decorator to mark a function as a task. + + Usage: + @task(name="send_email", queue="notifications") + def send_email(to: str, subject: str, body: str): + ... + """ + def decorator(func): + # Register task function + TASK_REGISTRY[name or f"{func.__module__}.{func.__name__}"] = { + "func": func, + "queue": queue, + "priority": priority, + "max_retries": max_retries, + "retry_backoff": retry_backoff + } + + # Add apply_async method to function + def apply_async(*args, **kwargs): + producer = get_current_producer() + return producer.apply_async( + task_func=func, + args=args, + kwargs=kwargs, + queue=queue, + priority=priority + ) + + func.apply_async = apply_async + func.delay = lambda *a, **k: producer.apply_async(func, a, k) + + return func + + return decorator + +# Global task registry +TASK_REGISTRY = {} +``` + +## Acceptance Criteria + +- [ ] Tasks can be enqueued for async execution +- [ ] Synchronous execution returns result directly +- [ ] Task priorities are respected +- [ ] Task chains execute sequentially +- [ ] Task groups execute in parallel +- [ ] Scheduled tasks execute at specified time +- [ ] Tasks can be cancelled + +## Notes + +**Trade-offs**: +- In-memory vs persistent task storage: Persistent for durability +- Direct function reference vs string name: Both supported + +**Performance**: +- Use connection pooling for database operations +- Batch enqueue operations for efficiency + +**Alternatives considered**: +- Celery-compatible API: Rejected, too complex +- Pure async API: Sync wrapper provided for convenience diff --git a/ai_coder_1/subtasks/Decomp-003-03.md b/ai_coder_1/subtasks/Decomp-003-03.md new file mode 100644 index 0000000..560d15e --- /dev/null +++ b/ai_coder_1/subtasks/Decomp-003-03.md @@ -0,0 +1,476 @@ +# Subtask: Task Worker Implementation + +**Parent Task**: Decomp/003 +**Subtask ID**: Decomp/003-03 +**Dependencies**: Decomp-003-01 (Database Schema), Decomp-003-02 (Task Producer API) + +## Description + +Implement task worker that polls queues, executes tasks, and reports results. Worker must support concurrent task execution, graceful shutdown, and auto-recovery from failures. + +## Requirements + +- Poll task queues for pending tasks +- Execute task functions with provided arguments +- Support concurrent task execution (configurable concurrency) +- Report task results (success/failure) to database +- Send heartbeats to indicate worker liveness +- Handle graceful shutdown (complete running tasks before exit) +- Auto-reconnection to broker after connection loss +- Support multiple queues per worker +- Task timeout enforcement +- Worker registration on startup + +## Technical Specifications + +**Worker core implementation**: +```python +import asyncio +import signal +import uuid +import os +import traceback +from typing import Set, Optional, List, Dict, Any +from datetime import datetime, timezone +from dataclasses import dataclass +import logging + +logger = logging.getLogger(__name__) + +@dataclass +class WorkerConfig: + """Worker configuration.""" + worker_name: Optional[str] = None # Auto-generated if None + queues: List[str] = None # Default: ["default"] + concurrency: int = 1 # Max concurrent tasks + prefetched_tasks: int = 2 # Tasks to prefetch + heartbeat_interval: float = 5.0 # Seconds + task_timeout: Optional[float] = None # Default task timeout + max_tasks_per_child: Optional[int] = None # Restart after N tasks + broker_url: str = "redis://localhost:6379" + db_url: str = "postgresql://localhost/tasks" + +class TaskWorker: + """Task execution worker.""" + + def __init__(self, config: WorkerConfig): + self.config = config + self.worker_name = config.worker_name or f"worker-{os.getpid()}-{uuid.uuid4().hex[:8]}" + self.queues = config.queues or ["default"] + self.concurrency = config.concurrency + self.running_tasks: Set[str] = set() + self.should_stop = False + self.task_count = 0 + + # Connections + self.broker = None + self.db = None + self.worker_id = None + + # Semaphore for concurrency control + self.semaphore = asyncio.Semaphore(self.concurrency) + + # Background tasks + self.heartbeat_task = None + self.scheduler_task = None + + async def start(self): + """Start the worker.""" + logger.info(f"Starting worker: {self.worker_name}") + + # Initialize connections + await self._connect() + + # Register worker + self.worker_id = await self._register_worker() + logger.info(f"Worker registered with ID: {self.worker_id}") + + # Start heartbeat task + self.heartbeat_task = asyncio.create_task(self._heartbeat_loop()) + + # Start scheduled task checker + self.scheduler_task = asyncio.create_task(self._scheduled_task_loop()) + + # Setup signal handlers + self._setup_signals() + + # Main worker loop + await self._main_loop() + + async def _connect(self): + """Initialize broker and database connections.""" + from .broker import RedisBroker + from .database import DatabaseConnection + + self.broker = RedisBroker(url=self.config.broker_url) + await self.broker.connect() + + self.db = DatabaseConnection(url=self.config.db_url) + await self.db.connect() + + async def _register_worker(self) -> int: + """Register worker in database.""" + async with self.db.acquire() as conn: + worker_id = await conn.fetchval( + """INSERT INTO workers (worker_name, hostname, pid, queues, concurrency) + VALUES ($1, $2, $3, $4, $5) + ON CONFLICT (worker_name) DO UPDATE + SET last_heartbeat = NOW(), current_tasks = 0 + RETURNING id""", + self.worker_name, + os.uname().nodename, + os.getpid(), + self.queues, + self.concurrency + ) + return worker_id + + async def _heartbeat_loop(self): + """Send periodic heartbeats.""" + while not self.should_stop: + try: + await self._send_heartbeat() + await asyncio.sleep(self.config.heartbeat_interval) + except asyncio.CancelledError: + break + except Exception as e: + logger.error(f"Heartbeat error: {e}") + await asyncio.sleep(self.config.heartbeat_interval) + + async def _send_heartbeat(self): + """Send heartbeat to database.""" + async with self.db.acquire() as conn: + await conn.execute( + """UPDATE workers + SET last_heartbeat = NOW(), current_tasks = $1 + WHERE id = $2""", + len(self.running_tasks), + self.worker_id + ) + + async def _scheduled_task_loop(self): + """Check for scheduled tasks ready to execute.""" + while not self.should_stop: + try: + await self._check_scheduled_tasks() + await asyncio.sleep(10) # Check every 10 seconds + except asyncio.CancelledError: + break + except Exception as e: + logger.error(f"Scheduled task check error: {e}") + await asyncio.sleep(10) + + async def _check_scheduled_tasks(self): + """Move scheduled tasks to pending queue.""" + async with self.db.acquire() as conn: + # Find tasks whose scheduled time has passed + rows = await conn.fetch( + """UPDATE tasks + SET status = 'pending' + WHERE status = 'pending' + AND scheduled_at <= NOW() + AND scheduled_at IS NOT NULL + RETURNING id, queue_id""" + ) + + for row in rows: + task_id = row["id"] + queue_id = row["queue_id"] + # Get queue name + queue_name = await conn.fetchval( + "SELECT name FROM task_queues WHERE id = $1", + queue_id + ) + # Add to broker queue + await self.broker.enqueue(queue_name, task_id) + + async def _main_loop(self): + """Main worker loop - fetch and execute tasks.""" + while not self.should_stop: + try: + # Check if we should restart (max tasks per child) + if (self.config.max_tasks_per_child and + self.task_count >= self.config.max_tasks_per_child): + logger.info(f"Reached max_tasks_per_child ({self.task_count}), restarting...") + await self._graceful_shutdown() + return + + # Try to fetch a task from any queue + task = await self._fetch_task() + + if task: + # Execute task in semaphore-controlled coroutine + asyncio.create_task(self._execute_task_wrapper(task)) + else: + # No tasks available, wait a bit + await asyncio.sleep(0.5) + + except asyncio.CancelledError: + break + except Exception as e: + logger.error(f"Error in main loop: {e}", exc_info=True) + await asyncio.sleep(1) + + async def _fetch_task(self) -> Optional[dict]: + """Fetch a task from the queue.""" + for queue_name in self.queues: + # Get queue ID + async with self.db.acquire() as conn: + queue_id = await conn.fetchval( + "SELECT id FROM task_queues WHERE name = $1", + queue_name + ) + + if not queue_id: + logger.warning(f"Queue not found: {queue_name}") + continue + + # Try to dequeue from broker + task_id = await self.broker.dequeue(queue_name) + + if task_id: + # Fetch full task data from database + async with self.db.acquire() as conn: + task = await conn.fetchrow( + """SELECT * FROM tasks WHERE id = $1""", + task_id + ) + + if task: + return dict(task) + + return None + + async def _execute_task_wrapper(self, task: dict): + """Wrapper to execute task with semaphore control.""" + async with self.semaphore: + task_id = task["id"] + self.running_tasks.add(task_id) + + try: + await self._execute_task(task) + except Exception as e: + logger.error(f"Error executing task {task_id}: {e}") + # Mark as failed + await self._mark_task_failed(task_id, str(e), traceback.format_exc()) + finally: + self.running_tasks.discard(task_id) + self.task_count += 1 + + async def _execute_task(self, task: dict): + """Execute a single task.""" + task_id = task["id"] + task_name = task["task_name"] + args = self._deserialize_args(task["args"]) + kwargs = self._deserialize_args(task["kwargs"]) + + logger.info(f"Executing task {task_id}: {task_name}") + + # Mark as running + await self._mark_task_running(task_id) + + # Get task function + from .producer import TASK_REGISTRY + task_info = TASK_REGISTRY.get(task_name) + + if not task_info: + raise ValueError(f"Task function not registered: {task_name}") + + func = task_info["func"] + + # Execute with timeout + timeout = self.config.task_timeout + try: + if asyncio.iscoroutinefunction(func): + if timeout: + result = await asyncio.wait_for( + func(*args, **kwargs), + timeout=timeout + ) + else: + result = await func(*args, **kwargs) + else: + if timeout: + result = await asyncio.wait_for( + asyncio.to_thread(func, *args, **kwargs), + timeout=timeout + ) + else: + result = await asyncio.to_thread(func, *args, **kwargs) + + # Mark as completed + await self._mark_task_completed(task_id, result) + logger.info(f"Task {task_id} completed successfully") + + except asyncio.TimeoutError: + error_msg = f"Task timed out after {timeout}s" + await self._mark_task_failed(task_id, error_msg, None) + logger.warning(f"Task {task_id} timed out") + + except Exception as e: + await self._mark_task_failed(task_id, str(e), traceback.format_exc()) + logger.error(f"Task {task_id} failed: {e}") + + async def _mark_task_running(self, task_id: str): + """Mark task as running.""" + async with self.db.acquire() as conn: + await conn.execute( + """UPDATE tasks + SET status = 'running', started_at = NOW(), worker_id = $1 + WHERE id = $2""", + self.worker_id, + task_id + ) + + async def _mark_task_completed(self, task_id: str, result: Any): + """Mark task as completed with result.""" + from .producer import TaskProducer + + result_json = TaskProducer._serialize_args(None, result) + + async with self.db.acquire() as conn: + await conn.execute( + """UPDATE tasks + SET status = 'completed', + result = $1, + completed_at = NOW(), + current_tasks = current_tasks - 1 + WHERE id = $2""", + result_json, + task_id + ) + + # Decrement worker task count + await conn.execute( + "UPDATE workers SET current_tasks = current_tasks - 1 WHERE id = $1", + self.worker_id + ) + + async def _mark_task_failed(self, task_id: str, error: str, tb: Optional[str]): + """Mark task as failed.""" + async with self.db.acquire() as conn: + await conn.execute( + """UPDATE tasks + SET status = 'failed', + error = $1, + traceback = $2, + completed_at = NOW() + WHERE id = $3""", + error, + tb, + task_id + ) + + # Decrement worker task count + await conn.execute( + "UPDATE workers SET current_tasks = current_tasks - 1 WHERE id = $1", + self.worker_id + ) + + def _deserialize_args(self, args_json: str) -> Any: + """Deserialize arguments from JSON.""" + import json + return json.loads(args_json) + + def _setup_signals(self): + """Setup signal handlers for graceful shutdown.""" + def signal_handler(sig, frame): + logger.info(f"Received signal {sig}, initiating graceful shutdown...") + asyncio.create_task(self._graceful_shutdown()) + + signal.signal(signal.SIGTERM, signal_handler) + signal.signal(signal.SIGINT, signal_handler) + + async def _graceful_shutdown(self): + """Gracefully shutdown the worker.""" + if self.should_stop: + return + + logger.info("Initiating graceful shutdown...") + self.should_stop = True + + # Wait for running tasks to complete + if self.running_tasks: + logger.info(f"Waiting for {len(self.running_tasks)} running tasks...") + while self.running_tasks: + await asyncio.sleep(0.5) + + # Cancel background tasks + if self.heartbeat_task: + self.heartbeat_task.cancel() + if self.scheduler_task: + self.scheduler_task.cancel() + + # Unregister worker + await self._unregister_worker() + + # Close connections + await self.broker.close() + await self.db.close() + + logger.info("Worker shutdown complete") + + async def _unregister_worker(self): + """Unregister worker from database.""" + async with self.db.acquire() as conn: + await conn.execute( + "DELETE FROM workers WHERE id = $1", + self.worker_id + ) +``` + +**Worker CLI**: +```python +import click +import asyncio + +@click.command() +@click.option('--queues', '-Q', multiple=True, default=['default']) +@click.option('--concurrency', '-c', default=1, type=int) +@click.option('--hostname', '-n', default=None) +@click.option('--loglevel', '-l', default='INFO') +def worker(queues, concurrency, hostname, loglevel): + """Start a task worker.""" + import logging + logging.basicConfig( + level=getattr(logging, loglevel), + format='%(asctime)s [%(levelname)s] %(message)s' + ) + + config = WorkerConfig( + worker_name=hostname, + queues=list(queues), + concurrency=concurrency + ) + + w = TaskWorker(config) + asyncio.run(w.start()) + +if __name__ == '__main__': + worker() +``` + +## Acceptance Criteria + +- [ ] Worker successfully registers on startup +- [ ] Worker polls queues and executes tasks +- [ ] Concurrency limit is respected +- [ ] Heartbeats sent at configured interval +- [ ] Graceful shutdown waits for running tasks +- [ ] Worker reconnects after connection loss +- [ ] Task timeouts are enforced +- [ ] Multiple queues supported per worker + +## Notes + +**Trade-offs**: +- Prefetch vs on-demand: On-demand for simplicity, can add prefetch later +- Process vs thread vs async: Async chosen for Python concurrency + +**Performance**: +- Connection pooling for database operations +- Batch heartbeat updates if needed + +**Alternatives considered**: +- Multi-process worker: Rejected, adds complexity +- Greenlets (gevent): Rejected, not compatible with modern async diff --git a/ai_coder_1/subtasks/Decomp-003-04.md b/ai_coder_1/subtasks/Decomp-003-04.md new file mode 100644 index 0000000..ec0c8df --- /dev/null +++ b/ai_coder_1/subtasks/Decomp-003-04.md @@ -0,0 +1,424 @@ +# Subtask: Task Retry and Error Handling + +**Parent Task**: Decomp/003 +**Subtask ID**: Decomp/003-04 +**Dependencies**: Decomp-003-01 (Database Schema), Decomp-003-03 (Task Worker Implementation) + +## Description + +Implement automatic retry logic for failed tasks with exponential backoff. Support configurable retry policies per task type, exception-based retry conditions, and manual retry triggering. + +## Requirements + +- Automatic retry on task failure +- Exponential backoff with jitter +- Configurable max retries per task +- Exception-based retry conditions (retry on specific exceptions only) +- Manual retry capability for failed tasks +- Retry history tracking +- Dead letter queue for permanently failed tasks +- Retry backoff storage (scheduled retry time) + +## Technical Specifications + +**Retry policy configuration**: +```python +from dataclasses import dataclass +from typing import Type, Tuple, Set, Optional, Callable +from enum import Enum + +class BackoffStrategy(Enum): + """Backoff strategies for retries.""" + EXPONENTIAL = "exponential" # 2^retry_count * base + LINEAR = "linear" # retry_count * base + FIBONACCI = "fibonacci" # Fibonacci sequence + FIXED = "fixed" # Always the same delay + +@dataclass +class RetryPolicy: + """Configuration for task retry behavior.""" + max_retries: int = 3 + backoff_base: int = 60 # Base delay in seconds + backoff_max: int = 3600 # Maximum delay in seconds + backoff_strategy: BackoffStrategy = BackoffStrategy.EXPONENTIAL + jitter: bool = True # Add randomness to prevent thundering herd + retry_on_exceptions: Optional[Tuple[Type[Exception], ...]] = None # None = retry on all + retry_on_exception_callback: Optional[Callable[[Exception], bool]] = None + + def should_retry(self, exception: Exception, retry_count: int) -> bool: + """Determine if task should be retried.""" + if retry_count >= self.max_retries: + return False + + if self.retry_on_exceptions is not None: + return isinstance(exception, self.retry_on_exceptions) + + if self.retry_on_exception_callback is not None: + return self.retry_on_exception_callback(exception) + + return True + + def get_backoff_delay(self, retry_count: int) -> int: + """Calculate backoff delay for given retry count.""" + if self.backoff_strategy == BackoffStrategy.EXPONENTIAL: + delay = self.backoff_base * (2 ** retry_count) + elif self.backoff_strategy == BackoffStrategy.LINEAR: + delay = self.backoff_base * (retry_count + 1) + elif self.backoff_strategy == BackoffStrategy.FIBONACCI: + delay = self.backoff_base * self._fibonacci(retry_count + 1) + else: # FIXED + delay = self.backoff_base + + delay = min(delay, self.backoff_max) + + # Add jitter: ±25% random variation + if self.jitter: + import random + delay = int(delay * (0.75 + random.random() * 0.5)) + + return delay + + @staticmethod + def _fibonacci(n: int) -> int: + """Calculate nth Fibonacci number.""" + a, b = 0, 1 + for _ in range(n): + a, b = b, a + b + return a + +# Default retry policies +DEFAULT_RETRY_POLICY = RetryPolicy(max_retries=3) +NO_RETRY_POLICY = RetryPolicy(max_retries=0) +AGGRESSIVE_RETRY_POLICY = RetryPolicy( + max_retries=10, + backoff_base=30, + backoff_max=1800 +) +``` + +**Retry handler implementation**: +```python +import asyncio +from datetime import datetime, timedelta, timezone +from typing import Optional +import logging + +logger = logging.getLogger(__name__) + +class RetryHandler: + """Handles task retry logic.""" + + def __init__(self, db, broker): + self.db = db + self.broker = broker + + async def handle_task_failure( + self, + task_id: str, + exception: Exception, + retry_count: int, + max_retries: int, + traceback: Optional[str] = None + ) -> bool: + """ + Handle a failed task and determine if it should be retried. + + Returns: + True if task was scheduled for retry, False if sent to DLQ + """ + # Get retry policy for this task type + from .producer import TASK_REGISTRY + task_name = await self._get_task_name(task_id) + task_info = TASK_REGISTRY.get(task_name, {}) + retry_policy = task_info.get("retry_policy", DEFAULT_RETRY_POLICY) + + # Override max_retries from task if specified + if max_retries != retry_policy.max_retries: + retry_policy = RetryPolicy( + max_retries=max_retries, + backoff_base=retry_policy.backoff_base, + backoff_max=retry_policy.backoff_max, + backoff_strategy=retry_policy.backoff_strategy, + jitter=retry_policy.jitter + ) + + # Check if should retry + if not retry_policy.should_retry(exception, retry_count): + logger.info(f"Task {task_id} will not be retried (max retries or non-retryable exception)") + await self._send_to_dlq(task_id, exception, traceback) + return False + + # Calculate backoff delay + delay = retry_policy.get_backoff_delay(retry_count) + retry_at = datetime.now(timezone.utc) + timedelta(seconds=delay) + + # Schedule retry + await self._schedule_retry(task_id, retry_count + 1, retry_at) + + logger.info( + f"Task {task_id} scheduled for retry at {retry_at.isoformat()} " + f"(attempt {retry_count + 1}/{max_retries}, delay: {delay}s)" + ) + + return True + + async def _schedule_retry(self, task_id: str, retry_count: int, retry_at: datetime): + """Schedule a task for retry.""" + async with self.db.acquire() as conn: + await conn.execute( + """UPDATE tasks + SET status = 'pending', + retry_count = $1, + scheduled_at = $2, + error = NULL, + traceback = NULL, + worker_id = NULL, + started_at = NULL + WHERE id = $3""", + retry_count, + retry_at, + task_id + ) + + # Log retry in history + await conn.execute( + """INSERT INTO task_history (task_id, status, details) + VALUES ($1, 'retry', $2)""", + task_id, + {"retry_count": retry_count, "scheduled_at": retry_at.isoformat()} + ) + + async def _send_to_dlq(self, task_id: str, exception: Exception, traceback: Optional[str]): + """Send failed task to dead letter queue.""" + async with self.db.acquire() as conn: + # Update task status + await conn.execute( + """UPDATE tasks + SET status = 'failed', + completed_at = NOW() + WHERE id = $1""", + task_id + ) + + # Add to DLQ table + await conn.execute( + """INSERT INTO dead_letter_queue (task_id, error, traceback, failed_at) + VALUES ($1, $2, $3, NOW()) + ON CONFLICT (task_id) DO NOTHING""", + task_id, + str(exception), + traceback + ) + + # Log in history + await conn.execute( + """INSERT INTO task_history (task_id, status, details) + VALUES ($1, 'dead_lettered', $2)""", + task_id, + {"error": str(exception)} + ) + + logger.warning(f"Task {task_id} sent to dead letter queue") + + async def _get_task_name(self, task_id: str) -> str: + """Get task name from database.""" + async with self.db.acquire() as conn: + return await conn.fetchval( + "SELECT task_name FROM tasks WHERE id = $1", + task_id + ) + + async def manual_retry(self, task_id: str) -> bool: + """ + Manually retry a failed task. + + Returns: + True if retry was scheduled + """ + async with self.db.acquire() as conn: + # Check if task exists and is failed + row = await conn.fetchrow( + """SELECT id, status, retry_count, max_retries + FROM tasks WHERE id = $1""", + task_id + ) + + if not row: + raise ValueError(f"Task {task_id} not found") + + if row["status"] not in ("failed", "cancelled"): + raise ValueError(f"Cannot retry task with status: {row['status']}") + + # Reset task for retry + await conn.execute( + """UPDATE tasks + SET status = 'pending', + retry_count = 0, + scheduled_at = NOW(), + error = NULL, + traceback = NULL, + worker_id = NULL, + started_at = NULL, + completed_at = NULL + WHERE id = $1""", + task_id + ) + + # Remove from DLQ if present + await conn.execute( + "DELETE FROM dead_letter_queue WHERE task_id = $1", + task_id + ) + + # Get queue name and add to broker + queue_name = await conn.fetchval( + """SELECT tq.name + FROM tasks t + JOIN task_queues tq ON t.queue_id = tq.id + WHERE t.id = $1""", + task_id + ) + + if queue_name: + await self.broker.enqueue(queue_name, task_id) + + # Log manual retry + await conn.execute( + """INSERT INTO task_history (task_id, status, details) + VALUES ($1, 'manual_retry', $2)""", + task_id, + {"timestamp": datetime.now(timezone.utc).isoformat()} + ) + + logger.info(f"Task {task_id} manually queued for retry") + return True + + async def retry_all_dlq(self, limit: int = 100) -> int: + """ + Retry all tasks in dead letter queue. + + Returns: + Number of tasks scheduled for retry + """ + async with self.db.acquire() as conn: + # Get tasks from DLQ + rows = await conn.fetch( + """SELECT task_id FROM dead_letter_queue ORDER BY failed_at LIMIT $1""", + limit + ) + + retried = 0 + for row in rows: + task_id = row["task_id"] + try: + await self.manual_retry(task_id) + retried += 1 + except Exception as e: + logger.error(f"Failed to retry task {task_id}: {e}") + + return retried +``` + +**Integration with worker**: +```python +# Modify TaskWorker._execute_task to use RetryHandler +async def _execute_task(self, task: dict): + """Execute a single task with retry handling.""" + task_id = task["id"] + task_name = task["task_name"] + args = self._deserialize_args(task["args"]) + kwargs = self._deserialize_args(task["kwargs"]) + retry_count = task.get("retry_count", 0) + max_retries = task.get("max_retries", 3) + + logger.info(f"Executing task {task_id}: {task_name} (attempt {retry_count + 1})") + + # Mark as running + await self._mark_task_running(task_id) + + # Get task function + from .producer import TASK_REGISTRY + task_info = TASK_REGISTRY.get(task_name) + + if not task_info: + error = ValueError(f"Task function not registered: {task_name}") + await self.retry_handler.handle_task_failure( + task_id, error, retry_count, max_retries + ) + return + + func = task_info["func"] + + # Execute with timeout + timeout = self.config.task_timeout + try: + if asyncio.iscoroutinefunction(func): + if timeout: + result = await asyncio.wait_for( + func(*args, **kwargs), + timeout=timeout + ) + else: + result = await func(*args, **kwargs) + else: + if timeout: + result = await asyncio.wait_for( + asyncio.to_thread(func, *args, **kwargs), + timeout=timeout + ) + else: + result = await asyncio.to_thread(func, *args, **kwargs) + + # Mark as completed + await self._mark_task_completed(task_id, result) + logger.info(f"Task {task_id} completed successfully") + + except Exception as e: + tb = traceback.format_exc() + logger.error(f"Task {task_id} failed: {e}") + + # Handle retry or send to DLQ + await self.retry_handler.handle_task_failure( + task_id, e, retry_count, max_retries, tb + ) +``` + +**Database extension for DLQ**: +```sql +-- Dead letter queue table +CREATE TABLE dead_letter_queue ( + id BIGSERIAL PRIMARY KEY, + task_id BIGINT NOT NULL UNIQUE REFERENCES tasks(id) ON DELETE CASCADE, + error TEXT NOT NULL, + traceback TEXT, + failed_at TIMESTAMP NOT NULL DEFAULT NOW(), + retry_count INTEGER DEFAULT 0, + last_retry_at TIMESTAMP, + metadata JSONB DEFAULT '{}'::jsonb +); + +CREATE INDEX idx_dlq_failed_at ON dead_letter_queue(failed_at DESC); +``` + +## Acceptance Criteria + +- [ ] Failed tasks are automatically retried up to max_retries +- [ ] Exponential backoff delay is calculated correctly +- [ ] Jitter is applied to prevent thundering herd +- [ ] Tasks exceeding max retries go to DLQ +- [ ] Manual retry can re-queue failed tasks +- [ ] Retry history is tracked in task_history +- [ ] Exception-based retry conditions work + +## Notes + +**Trade-offs**: +- Jitter vs deterministic scheduling: Jitter preferred for distributed systems +- Immediate vs scheduled retry: Scheduled to avoid overwhelming workers + +**Performance**: +- Batch DLQ retries to avoid spikes + +**Alternatives considered**: +- Celery-style autoretry_for: Similar approach adopted +- Immediate retry: Rejected, can cause cascading failures diff --git a/ai_coder_1/subtasks/Decomp-003-05.md b/ai_coder_1/subtasks/Decomp-003-05.md new file mode 100644 index 0000000..39c66f1 --- /dev/null +++ b/ai_coder_1/subtasks/Decomp-003-05.md @@ -0,0 +1,478 @@ +# Subtask: Cron Scheduler Implementation + +**Parent Task**: Decomp/003 +**Subtask ID**: Decomp/003-05 +**Dependencies**: Decomp-003-01 (Database Schema), Decomp-003-02 (Task Producer API) + +## Description + +Implement cron-like periodic task scheduler. Support standard cron expressions, dynamic schedule management, and distributed scheduling with leader election. + +## Requirements + +- Parse standard cron expressions (minute, hour, day, month, weekday) +- Schedule periodic tasks at defined intervals +- Support multiple periodic task definitions +- Dynamic add/remove/update of periodic tasks +- Prevent duplicate execution in multi-worker scenarios +- Track last run and next run times +- Support one-shot scheduled tasks +- Timezone-aware scheduling + +## Technical Specifications + +**Cron expression parser**: +```python +import re +from datetime import datetime, timedelta, timezone +from typing import List, Optional, Set +from dataclasses import dataclass + +@dataclass +class CronSchedule: + """Parsed cron schedule.""" + minute: Set[int] + hour: Set[int] + day: Set[int] + month: Set[int] + weekday: Set[int] # 0 = Monday, 6 = Sunday + + def matches(self, dt: datetime) -> bool: + """Check if datetime matches this schedule.""" + return ( + dt.minute in self.minute and + dt.hour in self.hour and + dt.day in self.day and + dt.month in self.month and + dt.weekday() in self.weekday + ) + + def next_run_time(self, after: datetime) -> datetime: + """Calculate next run time after given datetime.""" + # Start from next minute + dt = after.replace(second=0, microsecond=0) + timedelta(minutes=1) + + # Search forward (max 4 years = typical cron limit) + for _ in range(4 * 365 * 24 * 60): + if self.matches(dt): + return dt + dt += timedelta(minutes=1) + + raise ValueError("Could not find next run time within 4 years") + +class CronParser: + """Parse cron expressions.""" + + # Standard cron: minute hour day month weekday + PATTERN = re.compile( + r'^(\*|[\d,\-*/]+)\s+(\*|[\d,\-*/]+)\s+(\*|[\d,\-*/]+)\s+(\*|[\d,\-*/]+)\s+(\*|[\d,\-*/]+)$' + ) + + FIELD_RANGES = { + 'minute': (0, 59), + 'hour': (0, 23), + 'day': (1, 31), + 'month': (1, 12), + 'weekday': (0, 6), # 0=Monday, 6=Sunday + } + + @classmethod + def parse(cls, expression: str) -> CronSchedule: + """Parse cron expression.""" + m = cls.PATTERN.match(expression.strip()) + if not m: + raise ValueError(f"Invalid cron expression: {expression}") + + minute_str, hour_str, day_str, month_str, weekday_str = m.groups() + + return CronSchedule( + minute=cls._parse_field(minute_str, 0, 59), + hour=cls._parse_field(hour_str, 0, 23), + day=cls._parse_field(day_str, 1, 31), + month=cls._parse_field(month_str, 1, 12), + weekday=cls._parse_field(weekday_str, 0, 6), + ) + + @classmethod + def _parse_field(cls, field: str, min_val: int, max_val: int) -> Set[int]: + """Parse a single cron field.""" + result = set() + + if field == '*': + return set(range(min_val, max_val + 1)) + + # Handle comma-separated values + parts = field.split(',') + + for part in parts: + # Handle step (e.g., */5, 1-10/2) + if '/' in part: + base, step = part.split('/') + step = int(step) + if base == '*': + values = range(min_val, max_val + 1) + else: + values = cls._parse_range(base, min_val, max_val) + result.update(values[::step]) + + # Handle range (e.g., 1-5) + elif '-' in part: + result.update(cls._parse_range(part, min_val, max_val)) + + # Single value + else: + val = int(part) + if not (min_val <= val <= max_val): + raise ValueError(f"Value {val} out of range [{min_val}, {max_val}]") + result.add(val) + + return result + + @classmethod + def _parse_range(cls, range_str: str, min_val: int, max_val: int) -> List[int]: + """Parse a range expression (e.g., 1-5).""" + start, end = range_str.split('-') + start, end = int(start), int(end) + + if not (min_val <= start <= max_val): + raise ValueError(f"Range start {start} out of range") + if not (min_val <= end <= max_val): + raise ValueError(f"Range end {end} out of range") + + return list(range(start, end + 1)) + +# Common cron schedules +COMMON_SCHEDULES = { + "@every minute": "* * * * *", + "@every 5 minutes": "*/5 * * * *", + "@every 15 minutes": "*/15 * * * *", + "@every hour": "0 * * * *", + "@every day": "0 0 * * *", + "@every week": "0 0 * * 0", + "@every month": "0 0 1 * *", + "@every year": "0 0 1 1 *", + "@daily": "0 0 * * *", + "@weekly": "0 0 * * 0", + "@monthly": "0 0 1 * *", + "@yearly": "0 0 1 1 *", + "@annually": "0 0 1 1 *", +} +``` + +**Periodic task scheduler**: +```python +import asyncio +from datetime import datetime, timezone, timedelta +from typing import Dict, Optional +import logging + +logger = logging.getLogger(__name__) + +class PeriodicTaskScheduler: + """Scheduler for periodic/cron tasks.""" + + def __init__(self, db, broker, worker_name: str = "scheduler"): + self.db = db + self.broker = broker + self.worker_name = worker_name + self.running = False + self.leader = False + self.task = None + + async def start(self): + """Start the scheduler.""" + logger.info("Starting periodic task scheduler") + self.running = True + + # Start leader election and main loop + self.task = asyncio.create_task(self._main_loop()) + + async def stop(self): + """Stop the scheduler.""" + logger.info("Stopping periodic task scheduler") + self.running = False + if self.task: + self.task.cancel() + try: + await self.task + except asyncio.CancelledError: + pass + + async def _main_loop(self): + """Main scheduler loop.""" + while self.running: + try: + # Try to become leader + await self._elect_leader() + + if self.leader: + # Check and schedule due tasks + await self._check_and_schedule_tasks() + + # Wait before next check + await asyncio.sleep(10) + + except asyncio.CancelledError: + break + except Exception as e: + logger.error(f"Error in scheduler loop: {e}", exc_info=True) + await asyncio.sleep(10) + + async def _elect_leader(self): + """Participate in leader election using database advisory lock.""" + async with self.db.acquire() as conn: + # Try to acquire lock with 30 second timeout + result = await conn.fetchval( + """SELECT pg_try_advisory_lock( + (SELECT hashtext('periodic_scheduler')::bigint) + )""" + ) + + if result and not self.leader: + logger.info(f"{self.worker_name} became scheduler leader") + self.leader = True + elif not result and self.leader: + logger.info(f"{self.worker_name} lost scheduler leadership") + self.leader = False + + async def _check_and_schedule_tasks(self): + """Check for due periodic tasks and schedule them.""" + if not self.leader: + return + + async with self.db.acquire() as conn: + # Get active periodic tasks that are due + rows = await conn.fetch( + """SELECT * FROM periodic_tasks + WHERE is_active = TRUE + AND next_run_at <= NOW() + ORDER BY next_run_at + FOR UPDATE SKIP LOCKED""" + ) + + for row in rows: + await self._schedule_periodic_task(conn, dict(row)) + + async def _schedule_periodic_task(self, conn, task_info: dict): + """Schedule a single periodic task.""" + task_id = task_info["id"] + name = task_info["name"] + cron_expr = task_info["cron_expression"] + + try: + # Parse cron expression + cron_schedule = CronParser.parse(cron_expr) + + # Create the actual task + from .producer import TaskProducer + producer = TaskProducer(self.broker) + + # Generate unique task ID for this run + import uuid + run_id = str(uuid.uuid4()) + + # Enqueue the task + actual_task_id = await producer.apply_async( + task_func=task_info["task_name"], + args=task_info.get("args", []), + kwargs=task_info.get("kwargs", {}), + queue=await self._get_queue_name(conn, task_info["queue_id"]) + ) + + # Calculate next run time + now = datetime.now(timezone.utc) + next_run = cron_schedule.next_run_time(now) + + # Update periodic task + await conn.execute( + """UPDATE periodic_tasks + SET last_run_at = NOW(), + next_run_at = $1 + WHERE id = $2""", + next_run, + task_id + ) + + logger.info( + f"Scheduled periodic task '{name}' (run: {actual_task_id}, " + f"next run: {next_run.isoformat()})" + ) + + except Exception as e: + logger.error(f"Failed to schedule periodic task '{name}': {e}") + + async def _get_queue_name(self, conn, queue_id: int) -> str: + """Get queue name from ID.""" + return await conn.fetchval( + "SELECT name FROM task_queues WHERE id = $1", + queue_id + ) + + async def add_periodic_task( + self, + name: str, + task_name: str, + cron_expression: str, + queue: str = "default", + args: list = None, + kwargs: dict = None, + metadata: dict = None + ) -> int: + """Add a new periodic task.""" + # Parse cron expression to validate + CronParser.parse(cron_expression) + + # Calculate first run time + cron_schedule = CronParser.parse(cron_expression) + next_run = cron_schedule.next_run_time(datetime.now(timezone.utc)) + + async with self.db.acquire() as conn: + # Get queue ID + queue_id = await conn.fetchval( + "SELECT id FROM task_queues WHERE name = $1", + queue + ) + + if not queue_id: + raise ValueError(f"Queue not found: {queue}") + + # Insert periodic task + task_id = await conn.fetchval( + """INSERT INTO periodic_tasks + (name, task_name, cron_expression, queue_id, args, kwargs, + next_run_at, is_active, metadata) + VALUES ($1, $2, $3, $4, $5, $6, $7, TRUE, $8) + ON CONFLICT (name) DO UPDATE + SET task_name = EXCLUDED.task_name, + cron_expression = EXCLUDED.cron_expression, + queue_id = EXCLUDED.queue_id, + args = EXCLUDED.args, + kwargs = EXCLUDED.kwargs, + next_run_at = EXCLUDED.next_run_at, + is_active = TRUE + RETURNING id""", + name, + task_name, + cron_expression, + queue_id, + args or [], + kwargs or {}, + next_run, + metadata or {} + ) + + logger.info(f"Added periodic task '{name}' with schedule '{cron_expression}'") + return task_id + + async def remove_periodic_task(self, name: str) -> bool: + """Remove a periodic task.""" + async with self.db.acquire() as conn: + result = await conn.execute( + "DELETE FROM periodic_tasks WHERE name = $1", + name + ) + return result != "DELETE 0" + + async def disable_periodic_task(self, name: str) -> bool: + """Disable a periodic task without removing it.""" + async with self.db.acquire() as conn: + result = await conn.execute( + "UPDATE periodic_tasks SET is_active = FALSE WHERE name = $1", + name + ) + return result != "UPDATE 0" + + async def enable_periodic_task(self, name: str) -> bool: + """Enable a disabled periodic task.""" + async with self.db.acquire() as conn: + # Recalculate next run time + task_info = await conn.fetchrow( + "SELECT * FROM periodic_tasks WHERE name = $1", + name + ) + + if not task_info: + return False + + cron_schedule = CronParser.parse(task_info["cron_expression"]) + next_run = cron_schedule.next_run_time(datetime.now(timezone.utc)) + + await conn.execute( + """UPDATE periodic_tasks + SET is_active = TRUE, next_run_at = $1 + WHERE name = $2""", + next_run, + name + ) + return True + + async def list_periodic_tasks(self) -> list: + """List all periodic tasks.""" + async with self.db.acquire() as conn: + rows = await conn.fetch( + """SELECT name, task_name, cron_expression, is_active, + last_run_at, next_run_at + FROM periodic_tasks + ORDER BY name""" + ) + return [dict(row) for row in rows] +``` + +**Decorator for periodic tasks**: +```python +def periodic( + cron_expression: str, + name: str = None, + queue: str = "default" +): + """ + Decorator to register a function as a periodic task. + + Usage: + @periodic("0 0 * * *", name="daily_cleanup") + def cleanup_old_data(): + ... + """ + def decorator(func): + task_name = f"{func.__module__}.{func.__name__}" + periodic_name = name or task_name + + # Register as periodic task + PERIODIC_TASK_REGISTRY[periodic_name] = { + "task_name": task_name, + "cron_expression": cron_expression, + "queue": queue, + "func": func + } + + return func + + return decorator + +# Global periodic task registry +PERIODIC_TASK_REGISTRY = {} +``` + +## Acceptance Criteria + +- [ ] Standard cron expressions are parsed correctly +- [ ] Periodic tasks execute at scheduled times +- [ ] Only one scheduler instance schedules tasks (leader election) +- [ ] Next run times are calculated accurately +- [ ] Tasks can be added/removed/enabled/disabled dynamically +- [ ] Timezone handling works correctly +- [ ] Common schedules (@daily, @hourly) are supported + +## Notes + +**Trade-offs**: +- Database lock vs external coordinator: Database lock simpler +- Check interval: 10 seconds balances accuracy vs load + +**Performance**: +- Use SKIP LOCKED for concurrent scheduler instances +- Batch task scheduling to reduce transactions + +**Alternatives considered**: +- Celery beat: Similar approach adopted +- APScheduler integration: Rejected, built-in is sufficient diff --git a/ai_coder_1/subtasks/Decomp-003-06.md b/ai_coder_1/subtasks/Decomp-003-06.md new file mode 100644 index 0000000..cb2784a --- /dev/null +++ b/ai_coder_1/subtasks/Decomp-003-06.md @@ -0,0 +1,512 @@ +# Subtask: Task Monitoring and Health Checks + +**Parent Task**: Decomp/003 +**Subtask ID**: Decomp/003-06 +**Dependencies**: Decomp-003-01 (Database Schema), Decomp-003-03 (Task Worker Implementation) + +## Description + +Implement monitoring and health check system for task queue. Track worker status, task statistics, queue depths, and system health metrics. Provide HTTP API for monitoring dashboards and alerts. + +## Requirements + +- Real-time worker status monitoring +- Task execution statistics (success rate, avg duration) +- Queue depth monitoring +- Dead letter queue size tracking +- Health check endpoints (HTTP) +- Metrics export (Prometheus format) +- Alerts for abnormal conditions +- Task history and audit trail + +## Technical Specifications + +**Health check service**: +```python +from datetime import datetime, timedelta, timezone +from dataclasses import dataclass, field +from typing import List, Dict, Optional +from enum import Enum +import asyncio + +class HealthStatus(Enum): + """Health status levels.""" + HEALTHY = "healthy" + DEGRADED = "degraded" + UNHEALTHY = "unhealthy" + +@dataclass +class WorkerStats: + """Statistics for a single worker.""" + worker_id: int + worker_name: str + hostname: str + pid: int + queues: List[str] + concurrency: int + current_tasks: int + last_heartbeat: datetime + is_alive: bool + +@dataclass +class QueueStats: + """Statistics for a single queue.""" + queue_name: str + pending_count: int + running_count: int + completed_last_hour: int + failed_last_hour: int + avg_duration_seconds: float + +@dataclass +class SystemHealth: + """Overall system health status.""" + status: HealthStatus + total_workers: int + active_workers: int + total_queues: int + pending_tasks: int + running_tasks: int + stuck_tasks: int + dlq_size: int + timestamp: datetime = field(default_factory=lambda: datetime.now(timezone.utc)) + details: Dict = field(default_factory=dict) + +class MonitoringService: + """Service for monitoring task queue health.""" + + def __init__(self, db, broker): + self.db = db + self.broker = broker + + async def get_system_health(self) -> SystemHealth: + """Get overall system health status.""" + async with self.db.acquire() as conn: + # Get worker counts + total_workers = await conn.fetchval("SELECT COUNT(*) FROM workers") + active_workers = await conn.fetchval( + "SELECT COUNT(*) FROM workers WHERE last_heartbeat > NOW() - INTERVAL '1 minute'" + ) + + # Get task counts by status + pending_tasks = await conn.fetchval( + "SELECT COUNT(*) FROM tasks WHERE status = 'pending'" + ) + running_tasks = await conn.fetchval( + "SELECT COUNT(*) FROM tasks WHERE status = 'running'" + ) + + # Find stuck tasks (running but worker dead) + stuck_tasks = await conn.fetchval( + """SELECT COUNT(DISTINCT t.id) + FROM tasks t + WHERE t.status = 'running' + AND NOT EXISTS ( + SELECT 1 FROM workers w + WHERE w.id = t.worker_id + AND w.last_heartbeat > NOW() - INTERVAL '2 minutes' + )""" + ) + + # Get DLQ size + dlq_size = await conn.fetchval("SELECT COUNT(*) FROM dead_letter_queue") + + # Get queue count + total_queues = await conn.fetchval("SELECT COUNT(*) FROM task_queues WHERE is_active = TRUE") + + # Determine overall status + status = HealthStatus.HEALTHY + issues = [] + + if active_workers == 0: + status = HealthStatus.UNHEALTHY + issues.append("No active workers") + elif active_workers < total_workers // 2: + status = HealthStatus.DEGRADED + issues.append(f"Only {active_workers}/{total_workers} workers active") + + if stuck_tasks > 0: + status = HealthStatus.UNHEALTHY + issues.append(f"{stuck_tasks} stuck tasks detected") + + if dlq_size > 100: + status = HealthStatus.DEGRADED if status == HealthStatus.HEALTHY else status + issues.append(f"Large DLQ: {dlq_size} tasks") + + return SystemHealth( + status=status, + total_workers=total_workers, + active_workers=active_workers, + total_queues=total_queues, + pending_tasks=pending_tasks, + running_tasks=running_tasks, + stuck_tasks=stuck_tasks, + dlq_size=dlq_size, + details={"issues": issues} + ) + + async def get_worker_stats(self) -> List[WorkerStats]: + """Get statistics for all workers.""" + async with self.db.acquire() as conn: + rows = await conn.fetch( + """SELECT w.*, + (w.last_heartbeat > NOW() - INTERVAL '1 minute') AS is_alive + FROM workers w + ORDER BY w.last_heartbeat DESC""" + ) + + return [ + WorkerStats( + worker_id=row["id"], + worker_name=row["worker_name"], + hostname=row["hostname"], + pid=row["pid"], + queues=row.get("queues", []), + concurrency=row["concurrency"], + current_tasks=row["current_tasks"], + last_heartbeat=row["last_heartbeat"], + is_alive=row["is_alive"] + ) + for row in rows + ] + + async def get_queue_stats(self) -> List[QueueStats]: + """Get statistics for all queues.""" + async with self.db.acquire() as conn: + rows = await conn.fetch( + """SELECT tq.name, + COALESCE(pending.c, 0) AS pending_count, + COALESCE(running.c, 0) AS running_count, + COALESCE(completed.c, 0) AS completed_last_hour, + COALESCE(failed.c, 0) AS failed_last_hour, + COALESCE(avg_duration.avg_s, 0) AS avg_duration_seconds + FROM task_queues tq + LEFT JOIN ( + SELECT queue_id, COUNT(*) AS c + FROM tasks WHERE status = 'pending' + GROUP BY queue_id + ) pending ON pending.queue_id = tq.id + LEFT JOIN ( + SELECT queue_id, COUNT(*) AS c + FROM tasks WHERE status = 'running' + GROUP BY queue_id + ) running ON running.queue_id = tq.id + LEFT JOIN ( + SELECT t.queue_id, COUNT(*) AS c + FROM tasks t + WHERE t.status = 'completed' + AND t.completed_at > NOW() - INTERVAL '1 hour' + GROUP BY t.queue_id + ) completed ON completed.queue_id = tq.id + LEFT JOIN ( + SELECT t.queue_id, COUNT(*) AS c + FROM tasks t + WHERE t.status = 'failed' + AND t.completed_at > NOW() - INTERVAL '1 hour' + GROUP BY t.queue_id + ) failed ON failed.queue_id = tq.id + LEFT JOIN ( + SELECT t.queue_id, + AVG(EXTRACT(EPOCH FROM (t.completed_at - t.started_at))) AS avg_s + FROM tasks t + WHERE t.status = 'completed' + AND t.completed_at > NOW() - INTERVAL '24 hours' + AND t.started_at IS NOT NULL + GROUP BY t.queue_id + ) avg_duration ON avg_duration.queue_id = tq.id + WHERE tq.is_active = TRUE + ORDER BY tq.name""" + ) + + return [ + QueueStats( + queue_name=row["name"], + pending_count=row["pending_count"], + running_count=row["running_count"], + completed_last_hour=row["completed_last_hour"], + failed_last_hour=row["failed_last_hour"], + avg_duration_seconds=row["avg_duration_seconds"] or 0 + ) + for row in rows + ] + + async def get_task_history( + self, + task_id: str, + limit: int = 100 + ) -> List[dict]: + """Get history for a specific task.""" + async with self.db.acquire() as conn: + rows = await conn.fetch( + """SELECT th.status, th.timestamp, th.details, th.worker_id, w.worker_name + FROM task_history th + LEFT JOIN workers w ON w.id = th.worker_id + WHERE th.task_id = $1 + ORDER BY th.timestamp DESC + LIMIT $2""", + task_id, + limit + ) + return [dict(row) for row in rows] + + async def get_recent_tasks( + self, + status: str = None, + limit: int = 50 + ) -> List[dict]: + """Get recent tasks.""" + async with self.db.acquire() as conn: + query = """ + SELECT t.id, t.task_name, t.status, t.priority, + t.created_at, t.started_at, t.completed_at, + t.retry_count, w.worker_name + FROM tasks t + LEFT JOIN workers w ON w.id = t.worker_id + """ + params = [] + + if status: + query += " WHERE t.status = $1" + params.append(status) + + query += " ORDER BY t.created_at DESC LIMIT $2" + params.append(limit) + + rows = await conn.fetch(query, *params) + return [dict(row) for row in rows] + + async def get_statistics(self) -> dict: + """Get overall task statistics.""" + async with self.db.acquire() as conn: + # Task counts by status + status_counts = await conn.fetch( + """SELECT status, COUNT(*) AS count + FROM tasks + WHERE created_at > NOW() - INTERVAL '24 hours' + GROUP BY status""" + ) + + # Success rate + total = await conn.fetchval( + "SELECT COUNT(*) FROM tasks WHERE completed_at > NOW() - INTERVAL '24 hours'" + ) + successful = await conn.fetchval( + "SELECT COUNT(*) FROM tasks WHERE status = 'completed' AND completed_at > NOW() - INTERVAL '24 hours'" + ) + + success_rate = (successful / total * 100) if total > 0 else 0 + + # Average duration + avg_duration = await conn.fetchval( + """SELECT AVG(EXTRACT(EPOCH FROM (completed_at - started_at))) + FROM tasks + WHERE status = 'completed' + AND completed_at > NOW() - INTERVAL '24 hours' + AND started_at IS NOT NULL""" + ) or 0 + + # Top failing tasks + top_failing = await conn.fetch( + """SELECT task_name, COUNT(*) AS failure_count + FROM tasks + WHERE status = 'failed' + AND completed_at > NOW() - INTERVAL '24 hours' + GROUP BY task_name + ORDER BY failure_count DESC + LIMIT 10""" + ) + + return { + "status_counts": {r["status"]: r["count"] for r in status_counts}, + "success_rate_percent": round(success_rate, 2), + "avg_duration_seconds": round(avg_duration, 2), + "total_last_24h": total, + "top_failing_tasks": [dict(r) for r in top_failing] + } + + async def recover_stuck_tasks(self) -> int: + """Recover tasks that are stuck on dead workers.""" + async with self.db.acquire() as conn: + # Find stuck tasks + stuck_task_ids = await conn.fetch( + """SELECT t.id + FROM tasks t + WHERE t.status = 'running' + AND NOT EXISTS ( + SELECT 1 FROM workers w + WHERE w.id = t.worker_id + AND w.last_heartbeat > NOW() - INTERVAL '2 minutes' + )""" + ) + + recovered = 0 + for row in stuck_task_ids: + task_id = row["id"] + + # Check max retries + task_data = await conn.fetchrow( + "SELECT retry_count, max_retries FROM tasks WHERE id = $1", + task_id + ) + + if task_data["retry_count"] < task_data["max_retries"]: + # Reset to pending for retry + await conn.execute( + """UPDATE tasks + SET status = 'pending', + worker_id = NULL, + started_at = NULL + WHERE id = $1""", + task_id + ) + recovered += 1 + else: + # Mark as failed + await conn.execute( + """UPDATE tasks + SET status = 'failed', + error = 'Worker died during execution', + completed_at = NOW() + WHERE id = $1""", + task_id + ) + + return recovered +``` + +**HTTP monitoring API**: +```python +from fastapi import FastAPI, HTTPException +from fastapi.responses import JSONResponse, PlainTextResponse +from typing import List +import json + +app = FastAPI(title="Task Queue Monitor") + +@app.get("/health") +async def health_check(): + """Health check endpoint for load balancers.""" + monitoring = MonitoringService(db, broker) + health = await monitoring.get_system_health() + + if health.status == HealthStatus.UNHEALTHY: + raise HTTPException(status_code=503, detail="Service unhealthy") + + return { + "status": health.status.value, + "timestamp": health.timestamp.isoformat() + } + +@app.get("/health/detailed") +async def detailed_health(): + """Detailed health check.""" + monitoring = MonitoringService(db, broker) + return await monitoring.get_system_health() + +@app.get("/workers") +async def list_workers(): + """List all workers and their status.""" + monitoring = MonitoringService(db, broker) + return await monitoring.get_worker_stats() + +@app.get("/queues") +async def list_queues(): + """List all queues and their statistics.""" + monitoring = MonitoringService(db, broker) + return await monitoring.get_queue_stats() + +@app.get("/stats") +async def get_statistics(): + """Get overall statistics.""" + monitoring = MonitoringService(db, broker) + return await monitoring.get_statistics() + +@app.get("/tasks/{task_id}/history") +async def task_history(task_id: str): + """Get task history.""" + monitoring = MonitoringService(db, broker) + history = await monitoring.get_task_history(task_id) + if not history: + raise HTTPException(status_code=404, detail="Task not found") + return history + +@app.get("/tasks/recent") +async def recent_tasks(status: str = None, limit: int = 50): + """Get recent tasks.""" + monitoring = MonitoringService(db, broker) + return await monitoring.get_recent_tasks(status, limit) + +@app.post("/admin/recover-stuck") +async def recover_stuck(): + """Recover stuck tasks (admin endpoint).""" + monitoring = MonitoringService(db, broker) + recovered = await monitoring.recover_stuck_tasks() + return {"recovered_tasks": recovered} + +# Prometheus metrics endpoint +@app.get("/metrics", response_class=PlainTextResponse) +async def prometheus_metrics(): + """Export metrics in Prometheus format.""" + monitoring = MonitoringService(db, broker) + health = await monitoring.get_system_health() + queues = await monitoring.get_queue_stats() + stats = await monitoring.get_statistics() + + lines = [] + + # Worker metrics + lines.append(f"# HELP task_queue_workers_active Number of active workers") + lines.append(f"# TYPE task_queue_workers_active gauge") + lines.append(f"task_queue_workers_active {health.active_workers}") + + # Task metrics + lines.append(f"# HELP task_queue_pending Total pending tasks") + lines.append(f"# TYPE task_queue_pending gauge") + lines.append(f"task_queue_pending {health.pending_tasks}") + + lines.append(f"# HELP task_queue_running Total running tasks") + lines.append(f"# TYPE task_queue_running gauge") + lines.append(f"task_queue_running {health.running_tasks}") + + lines.append(f"# HELP task_queue_dlq_size Dead letter queue size") + lines.append(f"# TYPE task_queue_dlq_size gauge") + lines.append(f"task_queue_dlq_size {health.dlq_size}") + + # Per-queue metrics + for q in queues: + queue_name = q.queue_name.replace("-", "_") + lines.append(f'task_queue_pending{{queue="{queue_name}"}} {q.pending_count}') + lines.append(f'task_queue_running{{queue="{queue_name}"}} {q.running_count}') + lines.append(f'task_queue_completed_hour{{queue="{queue_name}"}} {q.completed_last_hour}') + + # Success rate + lines.append(f"# HELP task_queue_success_rate Success rate percentage") + lines.append(f"# TYPE task_queue_success_rate gauge") + lines.append(f"task_queue_success_rate {stats['success_rate_percent']}") + + return "\n".join(lines) +``` + +## Acceptance Criteria + +- [ ] Health check endpoint returns correct status +- [ ] Worker statistics are accurate +- [ ] Queue statistics are accurate +- [ ] Prometheus metrics are exported +- [ ] Stuck tasks are detected +- [ ] Stuck task recovery works +- [ ] Task history is tracked + +## Notes + +**Trade-offs**: +- In-memory vs database aggregation: Database for consistency +- Real-time vs periodic: Periodic reduces load + +**Performance**: +- Cache statistics for 30 seconds +- Use materialized views for complex queries + +**Alternatives considered**: +- Prometheus client library: Direct export simpler +- Separate monitoring service: Integrated into main service diff --git a/ai_coder_1/subtasks/Decomp-003-07.md b/ai_coder_1/subtasks/Decomp-003-07.md new file mode 100644 index 0000000..b6251e1 --- /dev/null +++ b/ai_coder_1/subtasks/Decomp-003-07.md @@ -0,0 +1,395 @@ +# Subtask: Result Storage and Retrieval + +**Parent Task**: Decomp/003 +**Subtask ID**: Decomp/003-07 +**Dependencies**: Decomp-003-01 (Database Schema), Decomp-003-02 (Task Producer API) + +## Description + +Implement result storage backend with configurable retention policies. Support synchronous result waiting, asynchronous result polling, and result expiration. Provide both PostgreSQL and Redis-based result storage options. + +## Requirements + +- Store task results with configurable TTL +- Retrieve results by task ID +- Wait for results synchronously (blocking) +- Poll for results asynchronously +- Result expiration and cleanup +- Support both JSON and pickle serialization +- Result backend abstraction (PostgreSQL, Redis, in-memory) +- Result compression for large payloads + +## Technical Specifications + +**Result backend interface**: +```python +from abc import ABC, abstractmethod +from typing import Any, Optional +from datetime import timedelta +import pickle +import json +import gzip +import logging + +logger = logging.getLogger(__name__) + +class ResultSerializer(ABC): + """Abstract base for result serialization.""" + + @abstractmethod + def serialize(self, value: Any) -> bytes: + pass + + @abstractmethod + def deserialize(self, data: bytes) -> Any: + pass + +class JSONSerializer(ResultSerializer): + """JSON serializer (default, safe but limited types).""" + + def serialize(self, value: Any) -> bytes: + return json.dumps(value, default=str).encode('utf-8') + + def deserialize(self, data: bytes) -> Any: + return json.loads(data.decode('utf-8')) + +class PickleSerializer(ResultSerializer): + """Pickle serializer (supports Python objects but less safe).""" + + def serialize(self, value: Any) -> bytes: + return pickle.dumps(value) + + def deserialize(self, data: bytes) -> Any: + return pickle.loads(data) + +class CompressedSerializer(ResultSerializer): + """Wrapper that compresses serialized data.""" + + def __init__(self, inner: ResultSerializer, compression_level: int = 6): + self.inner = inner + self.level = compression_level + + def serialize(self, value: Any) -> bytes: + data = self.inner.serialize(value) + return gzip.compress(data, compresslevel=self.level) + + def deserialize(self, data: bytes) -> Any: + data = gzip.decompress(data) + return self.inner.deserialize(data) + +class ResultBackend(ABC): + """Abstract base for result storage backends.""" + + def __init__(self, serializer: ResultSerializer = None, default_ttl: timedelta = None): + self.serializer = serializer or JSONSerializer() + self.default_ttl = default_ttl or timedelta(days=1) + + @abstractmethod + async def store(self, task_id: str, result: Any, ttl: timedelta = None) -> bool: + """Store a task result.""" + pass + + @abstractmethod + async def get(self, task_id: str) -> Optional[Any]: + """Get a task result if available.""" + pass + + @abstractmethod + async def delete(self, task_id: str) -> bool: + """Delete a task result.""" + pass + + @abstractmethod + async def exists(self, task_id: str) -> bool: + """Check if result exists.""" + pass + + async def wait_for( + self, + task_id: str, + timeout: float = None, + interval: float = 0.5 + ) -> Any: + """Wait for result to be available.""" + import asyncio + start_time = asyncio.get_event_loop().time() + + while True: + result = await self.get(task_id) + if result is not None: + return result + + if timeout is not None: + elapsed = asyncio.get_event_loop().time() - start_time + if elapsed >= timeout: + raise TimeoutError(f"Result for task {task_id} not available within {timeout}s") + + await asyncio.sleep(interval) +``` + +**PostgreSQL result backend**: +```python +class PostgresResultBackend(ResultBackend): + """PostgreSQL-based result storage.""" + + def __init__(self, db, serializer: ResultSerializer = None, default_ttl: timedelta = None): + super().__init__(serializer, default_ttl) + self.db = db + + async def store(self, task_id: str, result: Any, ttl: timedelta = None) -> bool: + """Store result in database.""" + serialized = self.serializer.serialize(result) + + ttl = ttl or self.default_ttl + expires_at = datetime.now(timezone.utc) + ttl + + async with self.db.acquire() as conn: + await conn.execute( + """UPDATE tasks + SET result = $1, expires_at = $2 + WHERE id = $3""", + serialized.decode('utf-8') if isinstance(serialized, bytes) else serialized, + expires_at, + task_id + ) + return True + + async def get(self, task_id: str) -> Optional[Any]: + """Get result from database.""" + async with self.db.acquire() as conn: + row = await conn.fetchrow( + """SELECT result, status FROM tasks + WHERE id = $1 AND expires_at > NOW()""", + task_id + ) + + if not row: + return None + + if row["status"] != "completed": + # Task not completed yet + return None + + if not row["result"]: + return None + + # Deserialize + result_data = row["result"] + if isinstance(result_data, str): + result_data = result_data.encode('utf-8') + + return self.serializer.deserialize(result_data) + + async def delete(self, task_id: str) -> bool: + """Delete result from database.""" + async with self.db.acquire() as conn: + result = await conn.execute( + "UPDATE tasks SET result = NULL WHERE id = $1", + task_id + ) + return result != "UPDATE 0" + + async def exists(self, task_id: str) -> bool: + """Check if result exists.""" + async with self.db.acquire() as conn: + return await conn.fetchval( + "SELECT EXISTS(SELECT 1 FROM tasks WHERE id = $1 AND result IS NOT NULL AND expires_at > NOW())", + task_id + ) + + async def cleanup_expired(self) -> int: + """Remove expired results.""" + async with self.db.acquire() as conn: + result = await conn.execute( + "UPDATE tasks SET result = NULL WHERE expires_at <= NOW()" + ) + # Parse "UPDATE N" to get count + count = int(result.split()[-1]) if result else 0 + return count +``` + +**Redis result backend**: +```python +class RedisResultBackend(ResultBackend): + """Redis-based result storage (faster, but volatile).""" + + def __init__(self, redis_client, serializer: ResultSerializer = None, default_ttl: timedelta = None): + super().__init__(serializer, default_ttl) + self.redis = redis_client + + async def store(self, task_id: str, result: Any, ttl: timedelta = None) -> bool: + """Store result in Redis.""" + serialized = self.serializer.serialize(result) + ttl_seconds = int((ttl or self.default_ttl).total_seconds()) + + key = f"result:{task_id}" + await self.redis.setex(key, ttl_seconds, serialized) + return True + + async def get(self, task_id: str) -> Optional[Any]: + """Get result from Redis.""" + key = f"result:{task_id}" + data = await self.redis.get(key) + + if data is None: + return None + + return self.serializer.deserialize(data) + + async def delete(self, task_id: str) -> bool: + """Delete result from Redis.""" + key = f"result:{task_id}" + return await self.redis.delete(key) > 0 + + async def exists(self, task_id: str) -> bool: + """Check if result exists.""" + key = f"result:{task_id}" + return await self.redis.exists(key) > 0 + + async def cleanup_expired(self) -> int: + """No-op for Redis (handles TTL automatically).""" + return 0 +``` + +**In-memory result backend**: +```python +class InMemoryResultBackend(ResultBackend): + """In-memory result storage (for testing).""" + + def __init__(self, serializer: ResultSerializer = None, default_ttl: timedelta = None): + super().__init__(serializer, default_ttl) + self._storage = {} + self._expires = {} + + async def store(self, task_id: str, result: Any, ttl: timedelta = None) -> bool: + """Store result in memory.""" + serialized = self.serializer.serialize(result) + self._storage[task_id] = serialized + + ttl = ttl or self.default_ttl + self._expires[task_id] = datetime.now(timezone.utc) + ttl + return True + + async def get(self, task_id: str) -> Optional[Any]: + """Get result from memory.""" + # Check expiration + if task_id in self._expires: + if datetime.now(timezone.utc) > self._expires[task_id]: + del self._storage[task_id] + del self._expires[task_id] + return None + + data = self._storage.get(task_id) + if data is None: + return None + + return self.serializer.deserialize(data) + + async def delete(self, task_id: str) -> bool: + """Delete result from memory.""" + self._storage.pop(task_id, None) + self._expires.pop(task_id, None) + return True + + async def exists(self, task_id: str) -> bool: + """Check if result exists.""" + return task_id in self._storage + + async def cleanup_expired(self) -> int: + """Remove expired results.""" + now = datetime.now(timezone.utc) + expired = [k for k, v in self._expires.items() if now > v] + + for key in expired: + self._storage.pop(key, None) + self._expires.pop(key, None) + + return len(expired) +``` + +**Result client**: +```python +import asyncio +from typing import Optional, Any + +class ResultClient: + """Client for retrieving task results.""" + + def __init__(self, backend: ResultBackend): + self.backend = backend + + async def get(self, task_id: str) -> Optional[Any]: + """Get result, returns None if not ready.""" + return await self.backend.get(task_id) + + async def wait(self, task_id: str, timeout: float = None) -> Any: + """Wait for result to be ready.""" + return await self.backend.wait_for(task_id, timeout) + + async def is_ready(self, task_id: str) -> bool: + """Check if result is ready.""" + return await self.backend.exists(task_id) + + async def forget(self, task_id: str) -> bool: + """Remove result from backend.""" + return await self.backend.delete(task_id) + + async def get_all(self, task_ids: list) -> dict: + """Get multiple results.""" + results = {} + for task_id in task_ids: + results[task_id] = await self.get(task_id) + return results + + async def wait_all(self, task_ids: list, timeout: float = None) -> dict: + """Wait for all results.""" + tasks = [self.wait(tid, timeout) for tid in task_ids] + results = await asyncio.gather(*tasks, return_exceptions=True) + + return { + task_id: (result if not isinstance(result, Exception) else None) + for task_id, result in zip(task_ids, results) + } +``` + +**Integration with producer**: +```python +# Modify TaskProducer to store results +class TaskProducer: + def __init__(self, broker, result_backend: ResultBackend = None): + self.broker = broker + self.result_backend = result_backend + # ... rest of init + + async def get_result(self, task_id: str, timeout: float = None) -> Any: + """Get task result, waiting if necessary.""" + if self.result_backend: + client = ResultClient(self.result_backend) + return await client.wait(task_id, timeout) + else: + # Fallback to database + return await self._get_task_result(task_id) +``` + +## Acceptance Criteria + +- [ ] Results can be stored and retrieved +- [ ] TTL expiration works correctly +- [ ] Blocking wait times out correctly +- [ ] Multiple serialization formats supported +- [ ] Compression reduces large payload size +- [ ] Cleanup removes expired results + +## Notes + +**Trade-offs**: +- PostgreSQL vs Redis: PostgreSQL for persistence, Redis for speed +- JSON vs Pickle: JSON default for safety, Pickle opt-in + +**Performance**: +- Use Redis for hot results (frequent access) +- Use PostgreSQL for audit trail + +**Alternatives considered**: +- S3 for large results: Overkill for most use cases +- Memcached: Less feature-rich than Redis diff --git a/ai_coder_1/subtasks/Decomp-003-08.md b/ai_coder_1/subtasks/Decomp-003-08.md new file mode 100644 index 0000000..f26df6c --- /dev/null +++ b/ai_coder_1/subtasks/Decomp-003-08.md @@ -0,0 +1,515 @@ +# Subtask: Dead Letter Queue and Recovery + +**Parent Task**: Decomp/003 +**Subtask ID**: Decomp/003-08 +**Dependencies**: Decomp-003-01 (Database Schema), Decomp-003-04 (Task Retry and Error Handling) + +## Description + +Implement comprehensive dead letter queue (DLQ) management for permanently failed tasks. Provide inspection, manual retry, archival, and alerting capabilities for failed tasks. + +## Requirements + +- Store failed tasks with error details +- Inspect DLQ contents with filtering +- Manual retry for individual tasks +- Bulk retry operations +- DLQ archival to cold storage +- Alerting on DLQ size thresholds +- Automatic retry policies for specific errors +- DLQ statistics and reporting + +## Technical Specifications + +**Dead letter queue manager**: +```python +from datetime import datetime, timezone, timedelta +from typing import List, Dict, Optional +from dataclasses import dataclass, field +from enum import Enum +import logging + +logger = logging.getLogger(__name__) + +class DLQAction(Enum): + """Actions that can be taken on DLQ tasks.""" + RETRY = "retry" + DELETE = "delete" + ARCHIVE = "archive" + IGNORE = "ignore" + +@dataclass +class DLQTask: + """A task in the dead letter queue.""" + task_id: str + task_name: str + error: str + traceback: Optional[str] + failed_at: datetime + retry_count: int + args: List = field(default_factory=list) + kwargs: Dict = field(default_factory=dict) + metadata: Dict = field(default_factory=dict) + +@dataclass +class DLQStats: + """Statistics for the dead letter queue.""" + total_count: int + failures_by_task: Dict[str, int] + failures_by_error_type: Dict[str, int] + oldest_failure: Optional[datetime] + newest_failure: Optional[datetime] + avg_retry_count: float + +class DeadLetterQueueManager: + """Manager for dead letter queue operations.""" + + def __init__(self, db, broker, retry_handler): + self.db = db + self.broker = broker + self.retry_handler = retry_handler + + async def add_to_dlq( + self, + task_id: str, + error: Exception, + traceback: Optional[str] = None, + metadata: dict = None + ): + """Add a failed task to the DLQ.""" + async with self.db.acquire() as conn: + # Get task details + task = await conn.fetchrow( + """SELECT id, task_name, args, kwargs, retry_count + FROM tasks WHERE id = $1""", + task_id + ) + + if not task: + logger.warning(f"Task {task_id} not found, cannot add to DLQ") + return + + # Add to DLQ + await conn.execute( + """INSERT INTO dead_letter_queue (task_id, error, traceback, failed_at, metadata) + VALUES ($1, $2, $3, NOW(), $4) + ON CONFLICT (task_id) DO UPDATE + SET error = EXCLUDED.error, + traceback = EXCLUDED.traceback, + failed_at = EXCLUDED.failed_at""", + task_id, + str(error), + traceback, + metadata or {} + ) + + # Check if alert needed + await self._check_dlq_alerts(conn) + + logger.warning(f"Task {task_id} added to dead letter queue") + + async def get_dlq_tasks( + self, + limit: int = 100, + offset: int = 0, + task_name: str = None, + error_contains: str = None, + since: datetime = None + ) -> List[DLQTask]: + """Get tasks from the DLQ with optional filtering.""" + async with self.db.acquire() as conn: + query = """ + SELECT dlq.*, t.task_name, t.args, t.kwargs + FROM dead_letter_queue dlq + JOIN tasks t ON t.id = dlq.task_id + WHERE 1=1 + """ + params = [] + + if task_name: + query += " AND t.task_name LIKE $1" + params.append(f"%{task_name}%") + + if error_contains: + query += " AND dlq.error LIKE $2" + params.append(f"%{error_contains}%") + + if since: + query += " AND dlq.failed_at >= $3" + params.append(since) + + query += " ORDER BY dlq.failed_at DESC" + query += f" LIMIT ${len(params) + 1} OFFSET ${len(params) + 2}" + params.extend([limit, offset]) + + rows = await conn.fetch(query, *params) + + return [ + DLQTask( + task_id=row["task_id"], + task_name=row["task_name"], + error=row["error"], + traceback=row["traceback"], + failed_at=row["failed_at"], + retry_count=row.get("retry_count", 0), + args=row.get("args", []), + kwargs=row.get("kwargs", {}), + metadata=row.get("metadata", {}) + ) + for row in rows + ] + + async def get_dlq_stats(self) -> DLQStats: + """Get statistics about the DLQ.""" + async with self.db.acquire() as conn: + # Total count + total_count = await conn.fetchval("SELECT COUNT(*) FROM dead_letter_queue") + + # Failures by task name + failures_by_task = await conn.fetch( + """SELECT t.task_name, COUNT(*) as count + FROM dead_letter_queue dlq + JOIN tasks t ON t.id = dlq.task_id + GROUP BY t.task_name + ORDER BY count DESC + LIMIT 20""" + ) + + # Failures by error (group by first line of error) + failures_by_error = await conn.fetch( + """SELECT SPLIT_PART(error, E'\n', 1) as error_type, COUNT(*) as count + FROM dead_letter_queue + GROUP BY error_type + ORDER BY count DESC + LIMIT 20""" + ) + + # Oldest and newest + oldest = await conn.fetchval( + "SELECT MIN(failed_at) FROM dead_letter_queue" + ) + newest = await conn.fetchval( + "SELECT MAX(failed_at) FROM dead_letter_queue" + ) + + # Average retry count + avg_retry = await conn.fetchval( + """SELECT COALESCE(AVG(t.retry_count), 0) + FROM dead_letter_queue dlq + JOIN tasks t ON t.id = dlq.task_id""" + ) + + return DLQStats( + total_count=total_count, + failures_by_task={r["task_name"]: r["count"] for r in failures_by_task}, + failures_by_error_type={r["error_type"]: r["count"] for r in failures_by_error}, + oldest_failure=oldest, + newest_failure=newest, + avg_retry_count=float(avg_retry) if avg_retry else 0.0 + ) + + async def retry_task(self, task_id: str) -> bool: + """Retry a single task from the DLQ.""" + return await self.retry_handler.manual_retry(task_id) + + async def retry_multiple( + self, + task_ids: List[str], + delay_seconds: float = 0 + ) -> Dict[str, bool]: + """Retry multiple tasks.""" + import asyncio + + results = {} + + for task_id in task_ids: + try: + await self.retry_task(task_id) + results[task_id] = True + if delay_seconds > 0: + await asyncio.sleep(delay_seconds) + except Exception as e: + logger.error(f"Failed to retry task {task_id}: {e}") + results[task_id] = False + + return results + + async def retry_all( + self, + task_name_filter: str = None, + error_filter: str = None, + limit: int = 100 + ) -> int: + """Retry tasks matching filters.""" + tasks = await self.get_dlq_tasks( + limit=limit, + task_name=task_name_filter, + error_contains=error_filter + ) + + retried = 0 + for task in tasks: + if await self.retry_task(task.task_id): + retried += 1 + + return retried + + async def delete_task(self, task_id: str) -> bool: + """Remove a task from the DLQ (and mark task as permanently failed).""" + async with self.db.acquire() as conn: + result = await conn.execute( + "DELETE FROM dead_letter_queue WHERE task_id = $1", + task_id + ) + return result != "DELETE 0" + + async def delete_multiple(self, task_ids: List[str]) -> int: + """Delete multiple tasks from DLQ.""" + if not task_ids: + return 0 + + async with self.db.acquire() as conn: + result = await conn.execute( + f"DELETE FROM dead_letter_queue WHERE task_id = ANY($1)", + task_ids + ) + return int(result.split()[-1]) if result else 0 + + async def archive_old( + self, + older_than: timedelta = timedelta(days=30), + archive_table: str = "dead_letter_queue_archive" + ) -> int: + """Archive old DLQ entries to a separate table.""" + cutoff = datetime.now(timezone.utc) - older_than + + async with self.db.acquire() as conn: + # Create archive table if not exists + await conn.execute( + f"""CREATE TABLE IF NOT EXISTS {archive_table} ( + LIKE dead_letter_queue INCLUDING ALL + )""" + ) + + # Move old entries + result = await conn.execute( + f"""WITH moved AS ( + DELETE FROM dead_letter_queue + WHERE failed_at < $1 + RETURNING * + ) + INSERT INTO {archive_table} + SELECT * FROM moved""", + cutoff + ) + + return int(result.split()[-1]) if result else 0 + + async def get_archived( + self, + limit: int = 100, + archive_table: str = "dead_letter_queue_archive" + ) -> List[dict]: + """Get archived DLQ entries.""" + async with self.db.acquire() as conn: + rows = await conn.fetch( + f"""SELECT * FROM {archive_table} + ORDER BY failed_at DESC + LIMIT $1""", + limit + ) + return [dict(row) for row in rows] + + async def _check_dlq_alerts(self, conn): + """Check if DLQ size thresholds are exceeded.""" + count = await conn.fetchval("SELECT COUNT(*) FROM dead_letter_queue") + + # Get alert thresholds from config + thresholds = { + "warning": 50, + "critical": 100 + } + + if count >= thresholds["critical"]: + await self._send_alert("critical", count) + elif count >= thresholds["warning"]: + await self._send_alert("warning", count) + + async def _send_alert(self, level: str, count: int): + """Send an alert about DLQ size.""" + logger.warning(f"DLQ alert: {level} - {count} tasks in dead letter queue") + + # Here you could integrate with external alerting systems + # e.g., PagerDuty, Slack, email, etc. + + async def create_auto_retry_rule( + self, + error_pattern: str, + max_retries: int = 5, + backoff_seconds: int = 300 + ): + """Create a rule for auto-retrying specific errors.""" + async with self.db.acquire() as conn: + await conn.execute( + """INSERT INTO dlq_auto_retry_rules (error_pattern, max_retries, backoff_seconds) + VALUES ($1, $2, $3) + ON CONFLICT (error_pattern) DO UPDATE + SET max_retries = EXCLUDED.max_retries, + backoff_seconds = EXCLUDED.backoff_seconds""", + error_pattern, + max_retries, + backoff_seconds + ) + + async def process_auto_retry_rules(self) -> int: + """Process auto-retry rules against DLQ entries.""" + async with self.db.acquire() as conn: + # Get all rules + rules = await conn.fetch("SELECT * FROM dlq_auto_retry_rules WHERE is_active = TRUE") + + retried = 0 + + for rule in rules: + # Find matching DLQ entries + pattern = rule["error_pattern"] + max_retries = rule["max_retries"] + + rows = await conn.fetch( + """SELECT dlq.task_id, t.retry_count + FROM dead_letter_queue dlq + JOIN tasks t ON t.id = dlq.task_id + WHERE dlq.error LIKE $1 + AND t.retry_count < $2""", + f"%{pattern}%", + max_retries + ) + + for row in rows: + try: + await self.retry_task(row["task_id"]) + retried += 1 + except Exception as e: + logger.error(f"Auto-retry failed for task {row['task_id']}: {e}") + + return retried +``` + +**Database schema extensions**: +```sql +-- Auto-retry rules table +CREATE TABLE dlq_auto_retry_rules ( + id SERIAL PRIMARY KEY, + error_pattern VARCHAR(500) NOT NULL UNIQUE, + max_retries INTEGER DEFAULT 5, + backoff_seconds INTEGER DEFAULT 300, + is_active BOOLEAN DEFAULT TRUE, + created_at TIMESTAMP NOT NULL DEFAULT NOW(), + created_by VARCHAR(200) +); + +CREATE INDEX idx_dlq_rules_active ON dlq_auto_retry_rules(is_active); +``` + +**DLQ CLI commands**: +```python +import click +import json + +@click.group() +def dlq(): + """Dead letter queue management commands.""" + pass + +@dlq.command() +@click.option('--limit', '-l', default=50, type=int) +@click.option('--task-name', '-t', default=None) +@click.option('--error', '-e', default=None) +@click.option('--format', '-f', type=click.Choice(['table', 'json']), default='table') +def list(limit, task_name, error, format): + """List tasks in the dead letter queue.""" + manager = get_dlq_manager() + tasks = asyncio.run(manager.get_dlq_tasks( + limit=limit, + task_name=task_name, + error_contains=error + )) + + if format == 'json': + click.echo(json.dumps([asdict(t) for t in tasks], default=str)) + else: + # Table format + click.echo(f"Found {len(tasks)} tasks in DLQ") + for t in tasks[:20]: + click.echo(f" {t.task_id[:8]}... | {t.task_name} | {t.error[:50]}...") + +@dlq.command() +@click.argument('task_id') +def retry(task_id): + """Retry a task from the DLQ.""" + manager = get_dlq_manager() + success = asyncio.run(manager.retry_task(task_id)) + if success: + click.echo(f"Task {task_id} queued for retry") + else: + click.echo(f"Failed to retry task {task_id}", err=True) + +@dlq.command() +@click.option('--task-name', '-t', default=None) +@click.option('--error', '-e', default=None) +@click.option('--limit', '-l', default=100) +def retry_all(task_name, error, limit): + """Retry multiple tasks from the DLQ.""" + manager = get_dlq_manager() + count = asyncio.run(manager.retry_all( + task_name_filter=task_name, + error_filter=error, + limit=limit + )) + click.echo(f"Queued {count} tasks for retry") + +@dlq.command() +@click.option('--days', '-d', default=30, type=int) +def archive(days): + """Archive old DLQ entries.""" + manager = get_dlq_manager() + count = asyncio.run(manager.archive_old( + older_than=timedelta(days=days) + )) + click.echo(f"Archived {count} tasks") + +@dlq.command() +def stats(): + """Show DLQ statistics.""" + manager = get_dlq_manager() + stats = asyncio.run(manager.get_dlq_stats()) + + click.echo(f"Total tasks in DLQ: {stats.total_count}") + click.echo(f"Average retry count: {stats.avg_retry_count:.1f}") + click.echo("\nTop failures by task:") + for task, count in list(stats.failures_by_task.items())[:10]: + click.echo(f" {task}: {count}") +``` + +## Acceptance Criteria + +- [ ] Failed tasks are stored in DLQ +- [ ] DLQ can be listed and filtered +- [ ] Individual tasks can be retried +- [ ] Bulk retry operations work +- [ ] Old tasks can be archived +- [ ] DLQ statistics are accurate +- [ ] Auto-retry rules function correctly + +## Notes + +**Trade-offs**: +- Archive vs delete: Archive preserves audit trail +- Auto-retry complexity: Manual retry gives more control + +**Performance**: +- Archive in batches to avoid long transactions +- Index DLQ by failed_at for efficient queries + +**Alternatives considered**: +- External DLQ (S3, SQS): Database simpler for this use case +- Immediate alert on each failure: Batch alerts reduce noise diff --git a/ai_coder_1/subtasks/Decomp-003-09.md b/ai_coder_1/subtasks/Decomp-003-09.md new file mode 100644 index 0000000..8cf7b90 --- /dev/null +++ b/ai_coder_1/subtasks/Decomp-003-09.md @@ -0,0 +1,493 @@ +# Subtask: Rate Limiting and Task Throttling + +**Parent Task**: Decomp/003 +**Subtask ID**: Decomp/003-09 +**Dependencies**: Decomp-003-01 (Database Schema), Decomp-003-02 (Task Producer API) + +## Description + +Implement rate limiting and task throttling to prevent abuse and manage resource consumption. Support per-queue limits, per-task-type limits, and dynamic rate adjustment. + +## Requirements + +- Rate limit task enqueueing per queue +- Rate limit per task type/function +- Throttling based on system load +- Token bucket algorithm for smooth limits +- Configurable limits via database +- Burst allowance handling +- Priority queue bypass for high-priority tasks +- Rate limit statistics and monitoring + +## Technical Specifications + +**Token bucket rate limiter**: +```python +import asyncio +import time +from datetime import datetime, timezone, timedelta +from typing import Dict, Optional +from dataclasses import dataclass +import logging + +logger = logging.getLogger(__name__) + +@dataclass +class RateLimit: + """Rate limit configuration.""" + rate: float # Tokens per second + burst: int # Maximum bucket size (token capacity) + + def __post_init__(self): + if self.burst <= 0: + self.burst = int(self.rate) # Default burst to 1 second worth + +@dataclass +class RateLimitState: + """Runtime state for rate limiter.""" + tokens: float + last_update: float # Unix timestamp + +class TokenBucketLimiter: + """Token bucket rate limiter.""" + + def __init__(self): + # State: key -> (tokens, last_update) + self._state: Dict[str, RateLimitState] = {} + self._limits: Dict[str, RateLimit] = {} + self._lock = asyncio.Lock() + + def configure(self, key: str, rate: float, burst: int = None): + """Configure rate limit for a key.""" + self._limits[key] = RateLimit( + rate=rate, + burst=burst or int(rate) + ) + + async def acquire( + self, + key: str, + tokens: float = 1.0, + block: bool = True, + timeout: float = None + ) -> bool: + """ + Acquire tokens from the bucket. + + Args: + key: Bucket identifier + tokens: Number of tokens to acquire + block: Wait if tokens not available + timeout: Max wait time in seconds + + Returns: + True if acquired, False if would exceed timeout + """ + limit = self._limits.get(key) + if limit is None: + # No limit configured + return True + + async with self._lock: + now = time.time() + state = self._state.get(key) + + if state is None: + state = RateLimitState(tokens=limit.burst, last_update=now) + self._state[key] = state + + # Refill tokens based on elapsed time + elapsed = now - state.last_update + state.tokens = min(limit.burst, state.tokens + elapsed * limit.rate) + state.last_update = now + + # Check if enough tokens + if state.tokens >= tokens: + state.tokens -= tokens + return True + + if not block: + return False + + # Calculate wait time + deficit = tokens - state.tokens + wait_time = deficit / limit.rate + + if timeout is not None and wait_time > timeout: + return False + + # Wait outside lock, then retry + await asyncio.sleep(min(wait_time, timeout or wait_time)) + return await self.acquire(key, tokens, block=False) + + async def consume( + self, + key: str, + tokens: float = 1.0 + ) -> bool: + """Consume tokens without blocking (returns immediately).""" + return await self.acquire(key, tokens, block=False) + + def get_available_tokens(self, key: str) -> float: + """Get current token count for a key.""" + limit = self._limits.get(key) + if limit is None: + return float('inf') + + state = self._state.get(key) + if state is None: + return limit.burst + + now = time.time() + elapsed = now - state.last_update + return min(limit.burst, state.tokens + elapsed * limit.rate) + + def reset(self, key: str = None): + """Reset token bucket(s).""" + if key: + self._state.pop(key, None) + else: + self._state.clear() +``` + +**Rate limiting service**: +```python +class RateLimitingService: + """Service for rate limiting task operations.""" + + def __init__(self, db, redis=None): + self.db = db + self.redis = redis # Optional Redis for distributed rate limiting + self.local_limiter = TokenBucketLimiter() + self._initialized = False + + async def initialize(self): + """Load rate limit configurations from database.""" + if self._initialized: + return + + async with self.db.acquire() as conn: + # Load queue limits + queue_limits = await conn.fetch( + """SELECT name, rate_limit, burst_limit + FROM task_queues + WHERE rate_limit IS NOT NULL""" + ) + + for row in queue_limits: + self.local_limiter.configure( + key=f"queue:{row['name']}", + rate=row['rate_limit'], + burst=row.get('burst_limit') + ) + + # Load task type limits + task_limits = await conn.fetch( + """SELECT task_name, rate_limit, burst_limit + FROM task_rate_limits + WHERE is_active = TRUE""" + ) + + for row in task_limits: + self.local_limiter.configure( + key=f"task:{row['task_name']}", + rate=row['rate_limit'], + burst=row.get('burst_limit') + ) + + self._initialized = True + + async def check_enqueue_limit( + self, + queue_name: str, + task_name: str = None, + priority: int = 5 + ) -> tuple[bool, str]: + """ + Check if task can be enqueued under rate limits. + + Returns: + (allowed, reason) + """ + await self.initialize() + + # High priority tasks bypass rate limits + if priority <= 2: + return True, "high_priority_bypass" + + # Check queue limit + queue_key = f"queue:{queue_name}" + if not await self.local_limiter.consume(queue_key): + return False, f"queue_rate_limit_exceeded:{queue_name}" + + # Check task type limit + if task_name: + task_key = f"task:{task_name}" + if not await self.local_limiter.consume(task_key): + return False, f"task_rate_limit_exceeded:{task_name}" + + return True, "ok" + + async def wait_for_enqueue_slot( + self, + queue_name: str, + task_name: str = None, + timeout: float = 30.0 + ) -> bool: + """Wait until a slot is available under rate limits.""" + await self.initialize() + + tasks = [] + tasks.append(self.local_limiter.acquire(f"queue:{queue_name}", block=True, timeout=timeout)) + + if task_name: + tasks.append(self.local_limiter.acquire(f"task:{task_name}", block=True, timeout=timeout)) + + results = await asyncio.gather(*tasks, return_exceptions=True) + return all(r is True for r in results) + + async def set_queue_limit( + self, + queue_name: str, + rate: float, + burst: int = None + ): + """Set rate limit for a queue.""" + async with self.db.acquire() as conn: + await conn.execute( + """UPDATE task_queues + SET rate_limit = $1, burst_limit = $2 + WHERE name = $3""", + rate, + burst, + queue_name + ) + + self.local_limiter.configure(f"queue:{queue_name}", rate, burst) + + async def set_task_limit( + self, + task_name: str, + rate: float, + burst: int = None + ): + """Set rate limit for a task type.""" + async with self.db.acquire() as conn: + await conn.execute( + """INSERT INTO task_rate_limits (task_name, rate_limit, burst_limit, is_active) + VALUES ($1, $2, $3, TRUE) + ON CONFLICT (task_name) DO UPDATE + SET rate_limit = EXCLUDED.rate_limit, + burst_limit = EXCLUDED.burst_limit, + is_active = TRUE""", + task_name, + rate, + burst + ) + + self.local_limiter.configure(f"task:{task_name}", rate, burst) + + async def get_limit_stats(self) -> dict: + """Get current rate limit statistics.""" + await self.initialize() + + stats = { + "queues": {}, + "tasks": {}, + "global_available": {} + } + + for key, limit in self.local_limiter._limits.items(): + available = self.local_limiter.get_available_tokens(key) + prefix, name = key.split(":", 1) + + if prefix == "queue": + stats["queues"][name] = { + "rate": limit.rate, + "burst": limit.burst, + "available": available + } + elif prefix == "task": + stats["tasks"][name] = { + "rate": limit.rate, + "burst": limit.burst, + "available": available + } + + return stats + +class SystemThrottler: + """Throttle task processing based on system load.""" + + def __init__(self, db): + self.db = db + self._cpu_threshold = 80.0 # Percent + self._memory_threshold = 85.0 # Percent + self._queue_depth_threshold = 10000 # Tasks + + async def should_throttle(self, queue_name: str = None) -> tuple[bool, str]: + """ + Check if system is under load and should throttle. + + Returns: + (should_throttle, reason) + """ + checks = [] + + # Check queue depth + if queue_name: + depth = await self._get_queue_depth(queue_name) + if depth > self._queue_depth_threshold: + checks.append(f"queue_depth:{depth}") + + # Check running task count + running = await self._get_running_count() + if running > self._queue_depth_threshold: + checks.append(f"running_tasks:{running}") + + # Check DLQ size + dlq_size = await self._get_dlq_size() + if dlq_size > 100: + checks.append(f"dlq_size:{dlq_size}") + + if checks: + return True, ",".join(checks) + + return False, "ok" + + async def _get_queue_depth(self, queue_name: str) -> int: + """Get pending task count for queue.""" + async with self.db.acquire() as conn: + return await conn.fetchval( + """SELECT COUNT(*) + FROM tasks t + JOIN task_queues tq ON t.queue_id = tq.id + WHERE tq.name = $1 AND t.status = 'pending'""", + queue_name + ) + + async def _get_running_count(self) -> int: + """Get total running task count.""" + async with self.db.acquire() as conn: + return await conn.fetchval( + "SELECT COUNT(*) FROM tasks WHERE status = 'running'" + ) + + async def _get_dlq_size(self) -> int: + """Get dead letter queue size.""" + async with self.db.acquire() as conn: + return await conn.fetchval("SELECT COUNT(*) FROM dead_letter_queue") + + def set_thresholds(self, cpu: float = None, memory: float = None, queue_depth: int = None): + """Update throttling thresholds.""" + if cpu is not None: + self._cpu_threshold = cpu + if memory is not None: + self._memory_threshold = memory + if queue_depth is not None: + self._queue_depth_threshold = queue_depth +``` + +**Integration with task producer**: +```python +# Modify TaskProducer to check rate limits +class TaskProducer: + def __init__(self, broker, rate_limiter: RateLimitingService = None): + self.broker = broker + self.rate_limiter = rate_limiter + # ... rest of init + + async def apply_async( + self, + task_func, + args=None, + kwargs=None, + queue=None, + priority=TaskPriority.NORMAL, + **options + ) -> str: + """Apply a task with rate limiting.""" + + # Get task name + if callable(task_func): + task_name = f"{task_func.__module__}.{task_func.__name__}" + else: + task_name = task_func + + queue_name = queue or self.default_queue + + # Check rate limits + if self.rate_limiter: + allowed, reason = await self.rate_limiter.check_enqueue_limit( + queue_name=queue_name, + task_name=task_name, + priority=priority.value + ) + + if not allowed: + raise RateLimitError(f"Rate limit exceeded: {reason}") + + # Continue with normal enqueue logic + # ... (rest of apply_async implementation) +``` + +**Database schema extensions**: +```sql +-- Add rate limit columns to task_queues +ALTER TABLE task_queues +ADD COLUMN rate_limit FLOAT, -- Tokens per second +ADD COLUMN burst_limit INTEGER; -- Maximum bucket size + +-- Task-specific rate limits +CREATE TABLE task_rate_limits ( + id SERIAL PRIMARY KEY, + task_name VARCHAR(200) NOT NULL UNIQUE, + rate_limit FLOAT NOT NULL, + burst_limit INTEGER, + is_active BOOLEAN DEFAULT TRUE, + created_at TIMESTAMP NOT NULL DEFAULT NOW(), + updated_at TIMESTAMP NOT NULL DEFAULT NOW() +); + +CREATE INDEX idx_task_rate_limits_active ON task_rate_limits(task_name) WHERE is_active = TRUE; + +-- Trigger to update updated_at +CREATE TRIGGER task_rate_limits_updated_at + BEFORE UPDATE ON task_rate_limits + FOR EACH ROW + EXECUTE FUNCTION update_updated_at(); +``` + +**Custom exception**: +```python +class RateLimitError(Exception): + """Raised when rate limit is exceeded.""" + def __init__(self, message: str, retry_after: float = None): + super().__init__(message) + self.retry_after = retry_after +``` + +## Acceptance Criteria + +- [ ] Queue rate limits are enforced +- [ ] Task type rate limits are enforced +- [ ] High-priority tasks bypass limits +- [ ] Rate limits can be configured dynamically +- [ ] System throttling activates under load +- [ ] Rate limit stats are available +- [ ] Token bucket refills correctly + +## Notes + +**Trade-offs**: +- In-memory vs distributed limiter: In-memory for simplicity, Redis for distributed +- Reject vs delay: Prefer reject with retry-after for APIs + +**Performance**: +- Use Redis for distributed deployments +- Batch limit checks for multiple tasks + +**Alternatives considered**: +- Fixed window: Token bucket smoother +- Leaky bucket: Token bucket more flexible +- Sliding window log: More complex, less performant diff --git a/ai_coder_1/subtasks/Decomp-004-01.md b/ai_coder_1/subtasks/Decomp-004-01.md new file mode 100644 index 0000000..002048c --- /dev/null +++ b/ai_coder_1/subtasks/Decomp-004-01.md @@ -0,0 +1,522 @@ +# Subtask: Database Schema for Order Processing + +**Parent Task**: Decomp/004 +**Subtask ID**: Decomp-004-01 +**Dependencies**: None + +## Description + +Design and implement database schema for e-commerce order processing system. Support inventory management, order lifecycle, payment processing, and shipping with ACID guarantees for critical operations. + +## Requirements + +- Products and inventory tracking +- Shopping cart persistence +- Order lifecycle management (pending → paid → shipped → delivered) +- Payment transaction records +- Shipping information and labels +- Order cancellation and refund tracking +- Customer addresses and profiles +- Order history and audit trail + +## Technical Specifications + +**Database choice**: PostgreSQL for ACID compliance + +**Core schema**: +```sql +-- ============================================ +-- PRODUCTS AND INVENTORY +-- ============================================ + +CREATE TABLE products ( + id BIGSERIAL PRIMARY KEY, + sku VARCHAR(50) NOT NULL UNIQUE, + name VARCHAR(500) NOT NULL, + description TEXT, + category_id INTEGER REFERENCES categories(id), + price DECIMAL(10, 2) NOT NULL CHECK (price >= 0), + cost_price DECIMAL(10, 2) CHECK (cost_price >= 0), + weight_grams INTEGER, + is_active BOOLEAN DEFAULT TRUE, + is_digital BOOLEAN DEFAULT FALSE, + metadata JSONB DEFAULT '{}'::jsonb, + created_at TIMESTAMP NOT NULL DEFAULT NOW(), + updated_at TIMESTAMP NOT NULL DEFAULT NOW() +); + +CREATE INDEX idx_products_sku ON products(sku); +CREATE INDEX idx_products_category ON products(category_id); +CREATE INDEX idx_products_active ON products(is_active) WHERE is_active = TRUE; + +CREATE TABLE categories ( + id SERIAL PRIMARY KEY, + name VARCHAR(200) NOT NULL, + parent_id INTEGER REFERENCES categories(id), + path VARCHAR(500), -- e.g., "Electronics/Computers/Laptops" + metadata JSONB DEFAULT '{}'::jsonb, + created_at TIMESTAMP NOT NULL DEFAULT NOW() +); + +CREATE INDEX idx_categories_parent ON categories(parent_id); + +CREATE TABLE inventory_items ( + id BIGSERIAL PRIMARY KEY, + product_id BIGINT NOT NULL REFERENCES products(id) ON DELETE CASCADE, + location_id INTEGER REFERENCES inventory_locations(id), + quantity_on_hand INTEGER NOT NULL DEFAULT 0 CHECK (quantity_on_hand >= 0), + quantity_reserved INTEGER NOT NULL DEFAULT 0 CHECK (quantity_reserved >= 0), + quantity_available INTEGER GENERATED ALWAYS AS ( + quantity_on_hand - quantity_reserved + ) STORED, + reorder_threshold INTEGER DEFAULT 10, + reorder_amount INTEGER DEFAULT 50, + last_restocked_at TIMESTAMP, + metadata JSONB DEFAULT '{}'::jsonb, + updated_at TIMESTAMP NOT NULL DEFAULT NOW(), + UNIQUE(product_id, location_id) +); + +CREATE INDEX idx_inventory_product ON inventory_items(product_id); +CREATE INDEX idx_inventory_location ON inventory_items(location_id); +CREATE INDEX idx_inventory_reorder ON inventory_items(product_id) + WHERE quantity_available <= reorder_threshold; + +CREATE TABLE inventory_locations ( + id SERIAL PRIMARY KEY, + name VARCHAR(200) NOT NULL, + location_type VARCHAR(50) NOT NULL, -- 'warehouse', 'store', 'supplier' + address TEXT, + is_primary BOOLEAN DEFAULT FALSE, + metadata JSONB DEFAULT '{}'::jsonb, + created_at TIMESTAMP NOT NULL DEFAULT NOW() +); + +-- Inventory reservation locks (for order processing) +CREATE TABLE inventory_reservations ( + id BIGSERIAL PRIMARY KEY, + order_id BIGINT NOT NULL REFERENCES orders(id) ON DELETE CASCADE, + product_id BIGINT NOT NULL REFERENCES products(id), + quantity INTEGER NOT NULL CHECK (quantity > 0), + location_id INTEGER REFERENCES inventory_locations(id), + status VARCHAR(20) NOT NULL DEFAULT 'pending', -- pending, committed, released, expired + expires_at TIMESTAMP NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT NOW(), + committed_at TIMESTAMP +); + +CREATE INDEX idx_reservations_order ON inventory_reservations(order_id); +CREATE INDEX idx_reservations_product ON inventory_reservations(product_id); +CREATE INDEX idx_reservations_status ON inventory_reservations(status, expires_at) + WHERE status = 'pending'; + +-- ============================================ +-- CUSTOMERS +-- ============================================ + +CREATE TABLE customers ( + id BIGSERIAL PRIMARY KEY, + email VARCHAR(255) NOT NULL UNIQUE, + password_hash VARCHAR(255), + first_name VARCHAR(100), + last_name VARCHAR(100), + phone VARCHAR(50), + date_of_birth DATE, + is_active BOOLEAN DEFAULT TRUE, + email_verified BOOLEAN DEFAULT FALSE, + metadata JSONB DEFAULT '{}'::jsonb, + created_at TIMESTAMP NOT NULL DEFAULT NOW(), + updated_at TIMESTAMP NOT NULL DEFAULT NOW(), + last_login_at TIMESTAMP +); + +CREATE INDEX idx_customers_email ON customers(email); +CREATE INDEX idx_customers_active ON customers(is_active) WHERE is_active = TRUE; + +CREATE TABLE customer_addresses ( + id BIGSERIAL PRIMARY KEY, + customer_id BIGINT NOT NULL REFERENCES customers(id) ON DELETE CASCADE, + address_type VARCHAR(20) NOT NULL, -- 'billing', 'shipping' + is_default BOOLEAN DEFAULT FALSE, + first_name VARCHAR(100), + last_name VARCHAR(100), + company VARCHAR(200), + address_line1 VARCHAR(255) NOT NULL, + address_line2 VARCHAR(255), + city VARCHAR(100) NOT NULL, + state_province VARCHAR(100), + postal_code VARCHAR(20) NOT NULL, + country_code CHAR(2) NOT NULL, + phone VARCHAR(50), + metadata JSONB DEFAULT '{}'::jsonb, + created_at TIMESTAMP NOT NULL DEFAULT NOW(), + updated_at TIMESTAMP NOT NULL DEFAULT NOW() +); + +CREATE INDEX idx_addresses_customer ON customer_addresses(customer_id, address_type); + +-- ============================================ +-- SHOPPING CARTS +-- ============================================ + +CREATE TABLE shopping_carts ( + id BIGSERIAL PRIMARY KEY, + customer_id BIGINT REFERENCES customers(id) ON DELETE SET NULL, + session_id VARCHAR(255), -- For guest carts + created_at TIMESTAMP NOT NULL DEFAULT NOW(), + updated_at TIMESTAMP NOT NULL DEFAULT NOW(), + expires_at TIMESTAMP, + CHECK (customer_id IS NOT NULL OR session_id IS NOT NULL) +); + +CREATE INDEX idx_carts_customer ON shopping_carts(customer_id); +CREATE INDEX idx_carts_session ON shopping_carts(session_id); +CREATE INDEX idx_carts_expires ON shopping_carts(expires_at) + WHERE expires_at > NOW(); + +CREATE TABLE cart_items ( + id BIGSERIAL PRIMARY KEY, + cart_id BIGINT NOT NULL REFERENCES shopping_carts(id) ON DELETE CASCADE, + product_id BIGINT NOT NULL REFERENCES products(id), + quantity INTEGER NOT NULL CHECK (quantity > 0), + unit_price DECIMAL(10, 2) NOT NULL, -- Price at time of adding + product_snapshot JSONB, -- Product data snapshot + created_at TIMESTAMP NOT NULL DEFAULT NOW(), + updated_at TIMESTAMP NOT NULL DEFAULT NOW(), + UNIQUE(cart_id, product_id) +); + +CREATE INDEX idx_cart_items_cart ON cart_items(cart_id); + +-- ============================================ +-- ORDERS +-- ============================================ + +CREATE TABLE orders ( + id BIGSERIAL PRIMARY KEY, + order_number VARCHAR(50) NOT NULL UNIQUE, + customer_id BIGINT NOT NULL REFERENCES customers(id), + status VARCHAR(20) NOT NULL DEFAULT 'pending', + -- Status flow: pending -> processing -> paid -> shipped -> delivered + -- Alternative: pending -> cancelled + -- paid -> refunded + currency CHAR(3) NOT NULL DEFAULT 'USD', + subtotal DECIMAL(10, 2) NOT NULL CHECK (subtotal >= 0), + tax_amount DECIMAL(10, 2) NOT NULL DEFAULT 0 CHECK (tax_amount >= 0), + shipping_amount DECIMAL(10, 2) NOT NULL DEFAULT 0 CHECK (shipping_amount >= 0), + discount_amount DECIMAL(10, 2) NOT NULL DEFAULT 0 CHECK (discount_amount >= 0), + total_amount DECIMAL(10, 2) NOT NULL CHECK (total_amount >= 0), + paid_amount DECIMAL(10, 2) NOT NULL DEFAULT 0 CHECK (paid_amount >= 0), + refunded_amount DECIMAL(10, 2) NOT NULL DEFAULT 0 CHECK (refunded_amount >= 0), + + -- Addresses (snapshotted at order time) + billing_address JSONB NOT NULL, + shipping_address JSONB NOT NULL, + + -- Shipping + shipping_method VARCHAR(100), + shipping_carrier VARCHAR(100), + tracking_number VARCHAR(100), + estimated_delivery_at TIMESTAMP, + actual_delivery_at TIMESTAMP, + shipped_at TIMESTAMP, + + -- Payment + payment_method VARCHAR(50), + payment_provider VARCHAR(50), + paid_at TIMESTAMP, + + -- Timestamps + created_at TIMESTAMP NOT NULL DEFAULT NOW(), + updated_at TIMESTAMP NOT NULL DEFAULT NOW(), + completed_at TIMESTAMP, + cancelled_at TIMESTAMP, + cancelled_reason TEXT, + + metadata JSONB DEFAULT '{}'::jsonb +); + +CREATE INDEX idx_orders_customer ON orders(customer_id); +CREATE INDEX idx_orders_status ON orders(status); +CREATE INDEX idx_orders_created ON orders(created_at DESC); +CREATE INDEX idx_orders_number ON orders(order_number); +CREATE INDEX idx_orders_tracking ON orders(tracking_number); + +CREATE TABLE order_items ( + id BIGSERIAL PRIMARY KEY, + order_id BIGINT NOT NULL REFERENCES orders(id) ON DELETE CASCADE, + product_id BIGINT NOT NULL REFERENCES products(id), + sku VARCHAR(50) NOT NULL, + product_name VARCHAR(500) NOT NULL, + quantity INTEGER NOT NULL CHECK (quantity > 0), + unit_price DECIMAL(10, 2) NOT NULL, + tax_amount DECIMAL(10, 2) NOT NULL DEFAULT 0, + discount_amount DECIMAL(10, 2) NOT NULL DEFAULT 0, + total_amount DECIMAL(10, 2) NOT NULL, + product_snapshot JSONB, + created_at TIMESTAMP NOT NULL DEFAULT NOW() +); + +CREATE INDEX idx_order_items_order ON order_items(order_id); +CREATE INDEX idx_order_items_product ON order_items(product_id); + +-- ============================================ +-- PAYMENTS +-- ============================================ + +CREATE TABLE payment_transactions ( + id BIGSERIAL PRIMARY KEY, + order_id BIGINT NOT NULL REFERENCES orders(id), + transaction_id VARCHAR(100) NOT NULL UNIQUE, -- External provider ID + provider VARCHAR(50) NOT NULL, -- 'stripe', 'paypal', etc. + payment_method VARCHAR(50) NOT NULL, -- 'card', 'paypal', etc. + payment_method_details JSONB, -- Card last4, brand, etc. + amount DECIMAL(10, 2) NOT NULL, + currency CHAR(3) NOT NULL, + status VARCHAR(20) NOT NULL, -- pending, succeeded, failed, refunded + failure_reason TEXT, + created_at TIMESTAMP NOT NULL DEFAULT NOW(), + processed_at TIMESTAMP, + refunded_at TIMESTAMP, + metadata JSONB DEFAULT '{}'::jsonb +); + +CREATE INDEX idx_payments_order ON payment_transactions(order_id); +CREATE INDEX idx_payments_transaction ON payment_transactions(transaction_id); +CREATE INDEX idx_payments_status ON payment_transactions(status); + +-- Refunds +CREATE TABLE refunds ( + id BIGSERIAL PRIMARY KEY, + payment_transaction_id BIGINT NOT NULL REFERENCES payment_transactions(id), + refund_id VARCHAR(100), -- External provider refund ID + amount DECIMAL(10, 2) NOT NULL, + reason TEXT, + status VARCHAR(20) NOT NULL, -- pending, succeeded, failed + created_at TIMESTAMP NOT NULL DEFAULT NOW(), + processed_at TIMESTAMP, + metadata JSONB DEFAULT '{}'::jsonb +); + +CREATE INDEX idx_refunds_payment ON refunds(payment_transaction_id); + +-- ============================================ +-- SHIPPING +-- ============================================ + +CREATE TABLE shipping_labels ( + id BIGSERIAL PRIMARY KEY, + order_id BIGINT NOT NULL REFERENCES orders(id), + label_id VARCHAR(100) NOT NULL UNIQUE, -- Provider label ID + provider VARCHAR(50) NOT NULL, -- 'ups', 'fedex', 'usps' + service_level VARCHAR(100), -- 'ground', 'express', etc. + tracking_number VARCHAR(100) NOT NULL, + shipment_cost DECIMAL(10, 2) NOT NULL, + label_data BYTEA, -- PDF label data + from_address JSONB NOT NULL, + to_address JSONB NOT NULL, + package_details JSONB, -- weight, dimensions + status VARCHAR(20) DEFAULT 'created', -- created, shipped, delivered, exception + created_at TIMESTAMP NOT NULL DEFAULT NOW(), + shipped_at TIMESTAMP, + delivered_at TIMESTAMP, + metadata JSONB DEFAULT '{}'::jsonb +); + +CREATE INDEX idx_labels_order ON shipping_labels(order_id); +CREATE INDEX idx_labels_tracking ON shipping_labels(tracking_number); + +-- ============================================ +-- ORDER STATUS HISTORY +-- ============================================ + +CREATE TABLE order_status_history ( + id BIGSERIAL PRIMARY KEY, + order_id BIGINT NOT NULL REFERENCES orders(id) ON DELETE CASCADE, + from_status VARCHAR(20), + to_status VARCHAR(20) NOT NULL, + reason TEXT, + changed_by VARCHAR(100), -- User or system + created_at TIMESTAMP NOT NULL DEFAULT NOW(), + metadata JSONB DEFAULT '{}'::jsonb +); + +CREATE INDEX idx_status_history_order ON order_status_history(order_id, created_at DESC); + +-- ============================================ +-- NOTIFICATIONS +-- ============================================ + +CREATE TABLE notifications ( + id BIGSERIAL PRIMARY KEY, + customer_id BIGINT REFERENCES customers(id) ON DELETE SET NULL, + order_id BIGINT REFERENCES orders(id) ON DELETE SET NULL, + type VARCHAR(50) NOT NULL, -- 'email', 'sms', 'push' + template VARCHAR(100) NOT NULL, + status VARCHAR(20) NOT NULL DEFAULT 'pending', -- pending, sent, failed + recipient VARCHAR(255) NOT NULL, + subject VARCHAR(500), + body TEXT, + metadata JSONB DEFAULT '{}'::jsonb, + created_at TIMESTAMP NOT NULL DEFAULT NOW(), + sent_at TIMESTAMP, + failed_at TIMESTAMP, + error_message TEXT +); + +CREATE INDEX idx_notifications_customer ON notifications(customer_id); +CREATE INDEX idx_notifications_order ON notifications(order_id); +CREATE INDEX idx_notifications_status ON notifications(status); + +-- ============================================ +-- FUNCTIONS AND TRIGGERS +-- ============================================ + +-- Updated at trigger function +CREATE OR REPLACE FUNCTION update_updated_at() +RETURNS TRIGGER AS $$ +BEGIN + NEW.updated_at = NOW(); + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +-- Apply updated_at trigger +CREATE TRIGGER products_updated_at BEFORE UPDATE ON products + FOR EACH ROW EXECUTE FUNCTION update_updated_at(); + +CREATE TRIGGER customers_updated_at BEFORE UPDATE ON customers + FOR EACH ROW EXECUTE FUNCTION update_updated_at(); + +CREATE TRIGGER customer_addresses_updated_at BEFORE UPDATE ON customer_addresses + FOR EACH ROW EXECUTE FUNCTION update_updated_at(); + +CREATE TRIGGER shopping_carts_updated_at BEFORE UPDATE ON shopping_carts + FOR EACH ROW EXECUTE FUNCTION update_updated_at(); + +CREATE TRIGGER cart_items_updated_at BEFORE UPDATE ON cart_items + FOR EACH ROW EXECUTE FUNCTION update_updated_at(); + +CREATE TRIGGER orders_updated_at BEFORE UPDATE ON orders + FOR EACH ROW EXECUTE FUNCTION update_updated_at(); + +CREATE TRIGGER inventory_items_updated_at BEFORE UPDATE ON inventory_items + FOR EACH ROW EXECUTE FUNCTION update_updated_at(); + +-- Generate order number +CREATE OR REPLACE FUNCTION generate_order_number() +RETURNS TRIGGER AS $$ +BEGIN + NEW.order_number := 'ORD-' || TO_CHAR(NOW(), 'YYYYMMDD') || '-' || + LPAD(nextval('order_number_seq')::TEXT, 6, '0'); + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE SEQUENCE order_number_seq; + +CREATE TRIGGER orders_generate_number BEFORE INSERT ON orders + FOR EACH ROW EXECUTE FUNCTION generate_order_number(); + +-- Update cart totals +CREATE OR REPLACE FUNCTION update_cart_totals() +RETURNS TRIGGER AS $$ +BEGIN + UPDATE shopping_carts + SET updated_at = NOW() + WHERE id = NEW.cart_id; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER cart_items_update_totals AFTER INSERT OR UPDATE OR DELETE ON cart_items + FOR EACH ROW EXECUTE FUNCTION update_cart_totals(); + +-- Log order status changes +CREATE OR REPLACE FUNCTION log_order_status_change() +RETURNS TRIGGER AS $$ +BEGIN + IF OLD.status IS DISTINCT FROM NEW.status THEN + INSERT INTO order_status_history (order_id, from_status, to_status) + VALUES (NEW.id, OLD.status, NEW.status); + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER orders_log_status_change BEFORE UPDATE ON orders + FOR EACH ROW EXECUTE FUNCTION log_order_status_change(); + +-- ============================================ +-- VIEWS FOR REPORTING +-- ============================================ + +-- Order summary view +CREATE VIEW order_summary AS +SELECT + o.id, + o.order_number, + o.customer_id, + o.status, + o.total_amount, + o.paid_amount, + o.refunded_amount, + o.created_at, + o.paid_at, + o.shipped_at, + COUNT(DISTINCT oi.id) as item_count, + SUM(oi.quantity) as total_quantity +FROM orders o +LEFT JOIN order_items oi ON oi.order_id = o.id +GROUP BY o.id; + +-- Low inventory view +CREATE VIEW low_inventory AS +SELECT + p.id, + p.sku, + p.name, + i.quantity_on_hand, + i.quantity_reserved, + i.quantity_available, + i.reorder_threshold, + (i.quantity_available <= i.reorder_threshold) as needs_reorder +FROM products p +JOIN inventory_items i ON i.product_id = p.id +WHERE i.quantity_available <= i.reorder_threshold; + +-- Daily sales view +CREATE VIEW daily_sales AS +SELECT + DATE(created_at) as date, + COUNT(*) as order_count, + SUM(total_amount) as total_sales, + SUM(paid_amount) as total_paid +FROM orders +WHERE status NOT IN ('pending', 'cancelled') +GROUP BY DATE(created_at); +``` + +## Acceptance Criteria + +- [ ] All tables created without errors +- [ ] Foreign key constraints enforced +- [ ] Check constraints validate data +- [ ] Indexes created for common queries +- [ ] Triggers fire correctly +- [ ] Views return expected data +- [ ] Order numbers generate uniquely + +## Notes + +**Trade-offs**: +- JSONB for addresses: Snapshot at order time vs normalized. Chose snapshot for historical accuracy. +- Separate reservations table: Needed for concurrent order processing. + +**Scalability**: +- Partition orders by date for large deployments +- Consider read replicas for reporting queries + +**Alternatives considered**: +- NoSQL for orders: Rejected, need ACID for inventory +- Event sourcing: Added status history table as middle ground diff --git a/ai_coder_1/subtasks/Decomp-004-02.md b/ai_coder_1/subtasks/Decomp-004-02.md new file mode 100644 index 0000000..ee9def1 --- /dev/null +++ b/ai_coder_1/subtasks/Decomp-004-02.md @@ -0,0 +1,544 @@ +# Subtask: Shopping Cart Management + +**Parent Task**: Decomp/004 +**Subtask ID**: Decomp-004-02 +**Dependencies**: Decomp-004-01 (Database Schema) + +## Description + +Implement shopping cart service with support for both authenticated customers and guest sessions. Handle cart persistence, item management, price calculation, and cart-to-order conversion. + +## Requirements + +- Create and retrieve carts for customers and guests +- Add, update, remove items from cart +- Handle product availability checks +- Calculate cart totals (subtotal, tax, shipping) +- Support quantity validation +- Cart merging (guest cart → customer cart on login) +- Cart expiration for guest carts +- Product snapshot for price consistency + +## Technical Specifications + +**Cart service implementation**: +```python +from datetime import datetime, timedelta, timezone +from typing import Optional, List, Dict, Any +from dataclasses import dataclass, field +from decimal import Decimal +import uuid +import logging + +logger = logging.getLogger(__name__) + +@dataclass +class CartItem: + """Shopping cart item.""" + id: int + product_id: int + sku: str + name: str + quantity: int + unit_price: Decimal + total_price: Decimal + product_snapshot: dict = None + +@dataclass +class CartTotals: + """Calculated cart totals.""" + subtotal: Decimal + tax_amount: Decimal + shipping_amount: Decimal + discount_amount: Decimal + total: Decimal + currency: str = "USD" + +@dataclass +class ShoppingCart: + """Shopping cart with items and totals.""" + id: int + customer_id: Optional[int] + session_id: Optional[str] + items: List[CartItem] = field(default_factory=list) + totals: CartTotals = None + created_at: datetime = None + updated_at: datetime = None + expires_at: datetime = None + +class CartService: + """Service for managing shopping carts.""" + + def __init__(self, db, product_service, tax_service=None): + self.db = db + self.product_service = product_service + self.tax_service = tax_service + + async def get_or_create_cart( + self, + customer_id: int = None, + session_id: str = None + ) -> ShoppingCart: + """Get existing cart or create new one.""" + if not customer_id and not session_id: + session_id = str(uuid.uuid4()) + + async with self.db.acquire() as conn: + # Try to find existing cart + if customer_id: + cart = await conn.fetchrow( + """SELECT * FROM shopping_carts + WHERE customer_id = $1 + AND (expires_at IS NULL OR expires_at > NOW()) + ORDER BY created_at DESC + LIMIT 1""", + customer_id + ) + elif session_id: + cart = await conn.fetchrow( + """SELECT * FROM shopping_carts + WHERE session_id = $1 + AND (expires_at IS NULL OR expires_at > NOW()) + LIMIT 1""", + session_id + ) + else: + cart = None + + if cart: + return await self._load_cart(conn, dict(cart)) + + # Create new cart + new_cart = await conn.fetchrow( + """INSERT INTO shopping_carts (customer_id, session_id, expires_at) + VALUES ($1, $2, $3) + RETURNING *""", + customer_id, + session_id, + datetime.now(timezone.utc) + timedelta(days=7) if not customer_id else None + ) + + return await self._load_cart(conn, dict(new_cart)) + + async def _load_cart(self, conn, cart_data: dict) -> ShoppingCart: + """Load cart with items.""" + # Load cart items + items_rows = await conn.fetch( + """SELECT ci.*, p.sku, p.name + FROM cart_items ci + JOIN products p ON p.id = ci.product_id + WHERE ci.cart_id = $1""", + cart_data["id"] + ) + + items = [ + CartItem( + id=row["id"], + product_id=row["product_id"], + sku=row["sku"], + name=row["name"], + quantity=row["quantity"], + unit_price=Decimal(str(row["unit_price"])), + total_price=Decimal(str(row["unit_price"])) * row["quantity"], + product_snapshot=row.get("product_snapshot") + ) + for row in items_rows + ] + + return ShoppingCart( + id=cart_data["id"], + customer_id=cart_data["customer_id"], + session_id=cart_data["session_id"], + items=items, + created_at=cart_data["created_at"], + updated_at=cart_data["updated_at"], + expires_at=cart_data["expires_at"] + ) + + async def add_item( + self, + cart_id: int, + product_id: int, + quantity: int = 1 + ) -> CartItem: + """Add item to cart or update quantity if exists.""" + if quantity <= 0: + raise ValueError("Quantity must be positive") + + # Get product info and current price + product = await self.product_service.get_product(product_id) + if not product: + raise ValueError(f"Product {product_id} not found") + + if not product["is_active"]: + raise ValueError(f"Product {product_id} is not available") + + # Check inventory availability + available = await self.product_service.get_available_quantity(product_id) + if available < quantity: + raise ValueError(f"Insufficient inventory. Available: {available}") + + async with self.db.acquire() as conn: + # Check if item already exists in cart + existing = await conn.fetchrow( + """SELECT * FROM cart_items + WHERE cart_id = $1 AND product_id = $2""", + cart_id, product_id + ) + + if existing: + # Update quantity + new_quantity = existing["quantity"] + quantity + + if available < new_quantity: + raise ValueError(f"Insufficient inventory for quantity {new_quantity}") + + await conn.execute( + """UPDATE cart_items + SET quantity = $1, updated_at = NOW() + WHERE id = $2""", + new_quantity, existing["id"] + ) + + return CartItem( + id=existing["id"], + product_id=product_id, + sku=product["sku"], + name=product["name"], + quantity=new_quantity, + unit_price=Decimal(str(product["price"])), + total_price=Decimal(str(product["price"])) * new_quantity + ) + else: + # Create product snapshot + snapshot = { + "id": product["id"], + "sku": product["sku"], + "name": product["name"], + "price": str(product["price"]) + } + + # Add new item + item = await conn.fetchrow( + """INSERT INTO cart_items (cart_id, product_id, quantity, unit_price, product_snapshot) + VALUES ($1, $2, $3, $4, $5) + RETURNING *""", + cart_id, product_id, quantity, product["price"], snapshot + ) + + return CartItem( + id=item["id"], + product_id=product_id, + sku=product["sku"], + name=product["name"], + quantity=quantity, + unit_price=Decimal(str(product["price"])), + total_price=Decimal(str(product["price"])) * quantity, + product_snapshot=snapshot + ) + + async def update_item_quantity( + self, + cart_id: int, + item_id: int, + quantity: int + ) -> CartItem: + """Update cart item quantity.""" + if quantity <= 0: + await self.remove_item(cart_id, item_id) + return None + + async with self.db.acquire() as conn: + # Get item with product info + item = await conn.fetchrow( + """SELECT ci.*, p.sku, p.name + FROM cart_items ci + JOIN products p ON p.id = ci.product_id + WHERE ci.id = $1 AND ci.cart_id = $2""", + item_id, cart_id + ) + + if not item: + raise ValueError("Cart item not found") + + # Check availability + available = await self.product_service.get_available_quantity(item["product_id"]) + if available < quantity: + raise ValueError(f"Insufficient inventory. Available: {available}") + + await conn.execute( + """UPDATE cart_items + SET quantity = $1, updated_at = NOW() + WHERE id = $2""", + quantity, item_id + ) + + return CartItem( + id=item_id, + product_id=item["product_id"], + sku=item["sku"], + name=item["name"], + quantity=quantity, + unit_price=Decimal(str(item["unit_price"])), + total_price=Decimal(str(item["unit_price"])) * quantity + ) + + async def remove_item(self, cart_id: int, item_id: int): + """Remove item from cart.""" + async with self.db.acquire() as conn: + result = await conn.execute( + "DELETE FROM cart_items WHERE id = $1 AND cart_id = $2", + item_id, cart_id + ) + if result == "DELETE 0": + raise ValueError("Cart item not found") + + async def clear_cart(self, cart_id: int): + """Remove all items from cart.""" + async with self.db.acquire() as conn: + await conn.execute("DELETE FROM cart_items WHERE cart_id = $1", cart_id) + + async def calculate_totals( + self, + cart: ShoppingCart, + shipping_address: dict = None + ) -> CartTotals: + """Calculate cart totals including tax and shipping.""" + subtotal = sum(item.total_price for item in cart.items) + + # Calculate tax (if service available) + tax_amount = Decimal("0") + if self.tax_service and shipping_address: + tax_amount = await self.tax_service.calculate_tax( + cart.items, shipping_address + ) + + # Calculate shipping (simple flat rate for now) + shipping_amount = await self._calculate_shipping(cart, shipping_address) + + # Calculate discounts (placeholder) + discount_amount = Decimal("0") + + total = subtotal + tax_amount + shipping_amount - discount_amount + + return CartTotals( + subtotal=subtotal, + tax_amount=tax_amount, + shipping_amount=shipping_amount, + discount_amount=discount_amount, + total=total + ) + + async def _calculate_shipping( + self, + cart: ShoppingCart, + address: dict = None + ) -> Decimal: + """Calculate shipping cost.""" + # Free shipping for orders over $50 + if any(item.total_price >= Decimal("50") for item in cart.items): + return Decimal("0") + + # Default flat rate + return Decimal("9.99") + + async def merge_carts(self, source_cart_id: int, target_cart_id: int): + """Merge source cart into target cart (e.g., guest → customer).""" + async with self.db.acquire() as conn: + async with conn.transaction(): + # Get items from source cart + source_items = await conn.fetch( + "SELECT * FROM cart_items WHERE cart_id = $1", + source_cart_id + ) + + for item in source_items: + # Check if target has same product + existing = await conn.fetchrow( + """SELECT * FROM cart_items + WHERE cart_id = $1 AND product_id = $2""", + target_cart_id, item["product_id"] + ) + + if existing: + # Update quantity + await conn.execute( + """UPDATE cart_items + SET quantity = quantity + $1 + WHERE id = $2""", + item["quantity"], existing["id"] + ) + else: + # Move item to target cart + await conn.execute( + """UPDATE cart_items + SET cart_id = $1 + WHERE id = $2""", + target_cart_id, item["id"] + ) + + # Delete source cart + await conn.execute( + "DELETE FROM shopping_carts WHERE id = $1", + source_cart_id + ) + + async def delete_cart(self, cart_id: int): + """Delete cart completely.""" + async with self.db.acquire() as conn: + await conn.execute("DELETE FROM shopping_carts WHERE id = $1", cart_id) + + async def expire_guest_carts(self, older_than_days: int = 7): + """Delete expired guest carts.""" + async with self.db.acquire() as conn: + result = await conn.execute( + """DELETE FROM shopping_carts + WHERE customer_id IS NULL + AND expires_at < NOW()""" + ) + deleted = int(result.split()[-1]) if result else 0 + logger.info(f"Deleted {deleted} expired guest carts") + return deleted +``` + +**Cart API endpoints**: +```python +from fastapi import APIRouter, Depends, HTTPException, status +from pydantic import BaseModel +from typing import Optional, List + +router = APIRouter(prefix="/cart", tags=["cart"]) + +class AddItemRequest(BaseModel): + product_id: int + quantity: int = 1 + +class UpdateItemRequest(BaseModel): + item_id: int + quantity: int + +class CartResponse(BaseModel): + id: int + items: List[dict] + totals: dict + item_count: int + +@router.get("/", response_model=CartResponse) +async def get_cart( + customer_id: Optional[int] = None, + session_id: Optional[str] = None +): + """Get current shopping cart.""" + cart_service = get_cart_service() + cart = await cart_service.get_or_create_cart(customer_id, session_id) + cart.totals = await cart_service.calculate_totals(cart) + + return CartResponse( + id=cart.id, + items=[{ + "id": item.id, + "product_id": item.product_id, + "sku": item.sku, + "name": item.name, + "quantity": item.quantity, + "unit_price": str(item.unit_price), + "total_price": str(item.total_price) + } for item in cart.items], + totals={ + "subtotal": str(cart.totals.subtotal), + "tax": str(cart.totals.tax_amount), + "shipping": str(cart.totals.shipping_amount), + "total": str(cart.totals.total) + }, + item_count=sum(item.quantity for item in cart.items) + ) + +@router.post("/items") +async def add_to_cart( + request: AddItemRequest, + customer_id: Optional[int] = None, + session_id: Optional[str] = None +): + """Add item to cart.""" + cart_service = get_cart_service() + cart = await cart_service.get_or_create_cart(customer_id, session_id) + + try: + item = await cart_service.add_item( + cart.id, + request.product_id, + request.quantity + ) + return {"success": True, "item": {"id": item.id, "quantity": item.quantity}} + except ValueError as e: + raise HTTPException(status_code=400, detail=str(e)) + +@router.put("/items") +async def update_item( + request: UpdateItemRequest, + customer_id: Optional[int] = None, + session_id: Optional[str] = None +): + """Update cart item quantity.""" + cart_service = get_cart_service() + cart = await cart_service.get_or_create_cart(customer_id, session_id) + + try: + item = await cart_service.update_item_quantity( + cart.id, + request.item_id, + request.quantity + ) + if item: + return {"success": True, "quantity": item.quantity} + return {"success": True, "removed": True} + except ValueError as e: + raise HTTPException(status_code=400, detail=str(e)) + +@router.delete("/items/{item_id}") +async def remove_item( + item_id: int, + customer_id: Optional[int] = None, + session_id: Optional[str] = None +): + """Remove item from cart.""" + cart_service = get_cart_service() + cart = await cart_service.get_or_create_cart(customer_id, session_id) + await cart_service.remove_item(cart.id, item_id) + return {"success": True} + +@router.delete("/") +async def clear_cart( + customer_id: Optional[int] = None, + session_id: Optional[str] = None +): + """Clear all items from cart.""" + cart_service = get_cart_service() + cart = await cart_service.get_or_create_cart(customer_id, session_id) + await cart_service.clear_cart(cart.id) + return {"success": True} +``` + +## Acceptance Criteria + +- [ ] Carts can be created for customers and guests +- [ ] Items can be added, updated, removed +- [ ] Quantities are validated against inventory +- [ ] Cart totals are calculated correctly +- [ ] Guest carts expire after configured time +- [ ] Carts merge correctly on login +- [ ] Product prices are snapshotted + +## Notes + +**Trade-offs**: +- Session-only vs persistent carts: Persistent for better UX +- Real-time vs lazy availability check: Lazy for performance + +**Performance**: +- Cache cart data in Redis for frequently accessed carts +- Batch inventory checks for multiple items + +**Alternatives considered**: +- Client-side cart: Lost on device change +- Distributed cart storage: Adds complexity diff --git a/ai_coder_1/subtasks/Decomp-004-03.md b/ai_coder_1/subtasks/Decomp-004-03.md new file mode 100644 index 0000000..2f84479 --- /dev/null +++ b/ai_coder_1/subtasks/Decomp-004-03.md @@ -0,0 +1,464 @@ +# Subtask: Inventory Reservation and Locking + +**Parent Task**: Decomp/004 +**Subtask ID**: Decomp-004-03 +**Dependencies**: Decomp-004-01 (Database Schema) + +## Description + +Implement inventory reservation system with ACID guarantees to prevent overselling. Support optimistic locking, reservation expiration, and automatic release of stale reservations. + +## Requirements + +- Reserve inventory during checkout +- Prevent race conditions on concurrent orders +- Support reservation expiration (timeout) +- Release reservations on order cancellation +- Commit reservations on payment success +- Handle multiple inventory locations +- Query available inventory accurately +- Support backorders (optional) + +## Technical Specifications + +**Inventory reservation service**: +```python +from datetime import datetime, timedelta, timezone +from typing import List, Dict, Optional, Tuple +from dataclasses import dataclass +import logging +import asyncpg + +logger = logging.getLogger(__name__) + +@dataclass +class ReservationResult: + """Result of inventory reservation.""" + success: bool + reservation_id: Optional[int] = None + failed_items: List[dict] = None + reason: Optional[str] = None + +@dataclass +class InventoryStatus: + """Current inventory status for a product.""" + product_id: int + quantity_on_hand: int + quantity_reserved: int + quantity_available: int + locations: List[dict] = None + +class InventoryReservationService: + """Service for managing inventory reservations.""" + + def __init__(self, db, reservation_timeout_minutes: int = 30): + self.db = db + self.reservation_timeout = timedelta(minutes=reservation_timeout_minutes) + + async def get_inventory_status(self, product_id: int) -> InventoryStatus: + """Get current inventory status for a product.""" + async with self.db.acquire() as conn: + # Get aggregated inventory + row = await conn.fetchrow( + """SELECT + product_id, + COALESCE(SUM(quantity_on_hand), 0) as quantity_on_hand, + COALESCE(SUM(quantity_reserved), 0) as quantity_reserved, + COALESCE(SUM(quantity_available), 0) as quantity_available + FROM inventory_items + WHERE product_id = $1 + GROUP BY product_id""", + product_id + ) + + if not row: + return InventoryStatus( + product_id=product_id, + quantity_on_hand=0, + quantity_reserved=0, + quantity_available=0 + ) + + # Get location details + locations = await conn.fetch( + """SELECT il.*, l.name as location_name, l.location_type + FROM inventory_items il + JOIN inventory_locations l ON l.id = il.location_id + WHERE il.product_id = $1""", + product_id + ) + + return InventoryStatus( + product_id=product_id, + quantity_on_hand=row["quantity_on_hand"], + quantity_reserved=row["quantity_reserved"], + quantity_available=row["quantity_available"], + locations=[dict(l) for l in locations] + ) + + async def reserve_inventory( + self, + order_id: int, + items: List[dict], # [{product_id, quantity}] + location_id: Optional[int] = None + ) -> ReservationResult: + """ + Reserve inventory for an order. + + Uses SELECT FOR UPDATE SKIP LOCKED to handle concurrency. + """ + async with self.db.acquire() as conn: + try: + async with conn.transaction(): + # Check and reserve each item + reservation_ids = [] + failed_items = [] + + for item in items: + product_id = item["product_id"] + quantity = item["quantity"] + + # Find available inventory with row-level lock + if location_id: + # Specific location + location_ids = [location_id] + else: + # Any location with availability + location_ids = await conn.fetch( + """SELECT location_id + FROM inventory_items + WHERE product_id = $1 + AND quantity_available >= $2 + ORDER BY quantity_available DESC + FOR UPDATE""", + product_id, quantity + ) + + if not location_ids: + failed_items.append({ + "product_id": product_id, + "requested": quantity, + "available": await self._get_available_quantity(conn, product_id) + }) + continue + + # Use the first available location + loc_id = location_ids[0] if isinstance(location_ids[0], int) else location_ids[0]["location_id"] + + # Create reservation + reservation_id = await conn.fetchval( + """INSERT INTO inventory_reservations + (order_id, product_id, quantity, location_id, + status, expires_at) + VALUES ($1, $2, $3, $4, 'pending', $5) + RETURNING id""", + order_id, + product_id, + quantity, + loc_id, + datetime.now(timezone.utc) + self.reservation_timeout + ) + + # Update inventory reserved quantity + await conn.execute( + """UPDATE inventory_items + SET quantity_reserved = quantity_reserved + $1 + WHERE product_id = $2 AND location_id = $3""", + quantity, product_id, loc_id + ) + + reservation_ids.append(reservation_id) + + if failed_items: + # Rollback will release any reservations made + raise InsufficientInventoryError( + f"Insufficient inventory for products: " + f"{[f['product_id'] for f in failed_items]}" + ) + + return ReservationResult( + success=True, + reservation_id=reservation_ids[0] if len(reservation_ids) == 1 else None + ) + + except InsufficientInventoryError as e: + return ReservationResult( + success=False, + failed_items=failed_items, + reason=str(e) + ) + except Exception as e: + logger.error(f"Error reserving inventory: {e}") + return ReservationResult( + success=False, + reason=f"Database error: {str(e)}" + ) + + async def _get_available_quantity(self, conn, product_id: int) -> int: + """Get available quantity for a product.""" + return await conn.fetchval( + """SELECT COALESCE(SUM(quantity_available), 0) + FROM inventory_items + WHERE product_id = $1""", + product_id + ) or 0 + + async def commit_reservations(self, order_id: int) -> bool: + """ + Commit reservations (permanently deduct inventory). + + Called after successful payment. + """ + async with self.db.acquire() as conn: + async with conn.transaction(): + # Get all pending reservations for this order + reservations = await conn.fetch( + """SELECT * FROM inventory_reservations + WHERE order_id = $1 AND status = 'pending' + FOR UPDATE""", + order_id + ) + + if not reservations: + return True + + # Commit each reservation + for res in reservations: + # Deduct from on-hand, reduce reserved + await conn.execute( + """UPDATE inventory_items + SET quantity_on_hand = quantity_on_hand - $1, + quantity_reserved = quantity_reserved - $1 + WHERE product_id = $2 AND location_id = $3""", + res["quantity"], res["product_id"], res["location_id"] + ) + + # Mark reservation as committed + await conn.execute( + """UPDATE inventory_reservations + SET status = 'committed', + committed_at = NOW() + WHERE id = $1""", + res["id"] + ) + + logger.info(f"Committed {len(reservations)} inventory reservations for order {order_id}") + return True + + async def release_reservations(self, order_id: int) -> bool: + """ + Release reservations (return to available inventory). + + Called on order cancellation or payment failure. + """ + async with self.db.acquire() as conn: + async with conn.transaction(): + # Get all pending reservations for this order + reservations = await conn.fetch( + """SELECT * FROM inventory_reservations + WHERE order_id = $1 AND status = 'pending' + FOR UPDATE""", + order_id + ) + + if not reservations: + return True + + # Release each reservation + for res in reservations: + # Reduce reserved quantity + await conn.execute( + """UPDATE inventory_items + SET quantity_reserved = quantity_reserved - $1 + WHERE product_id = $2 AND location_id = $3""", + res["quantity"], res["product_id"], res["location_id"] + ) + + # Mark reservation as released + await conn.execute( + """UPDATE inventory_reservations + SET status = 'released' + WHERE id = $1""", + res["id"] + ) + + logger.info(f"Released {len(reservations)} inventory reservations for order {order_id}") + return True + + async def expire_reservations(self) -> int: + """ + Find and release expired reservations. + + Should be run periodically (e.g., every 5 minutes). + """ + async with self.db.acquire() as conn: + async with conn.transaction(): + # Find expired reservations + expired = await conn.fetch( + """SELECT * FROM inventory_reservations + WHERE status = 'pending' + AND expires_at < NOW() + FOR UPDATE""" + ) + + if not expired: + return 0 + + # Release each expired reservation + for res in expired: + # Reduce reserved quantity + await conn.execute( + """UPDATE inventory_items + SET quantity_reserved = quantity_reserved - $1 + WHERE product_id = $2 AND location_id = $3""", + res["quantity"], res["product_id"], res["location_id"] + ) + + # Mark reservation as expired + await conn.execute( + """UPDATE inventory_reservations + SET status = 'expired' + WHERE id = $1""", + res["id"] + ) + + # Log order for potential follow-up + logger.warning( + f"Expired reservation {res['id']} for order {res['order_id']}, " + f"product {res['product_id']}, quantity {res['quantity']}" + ) + + return len(expired) + + async def check_availability( + self, + items: List[dict] + ) -> Dict[int, bool]: + """ + Check if all items are available without reserving. + + Returns {product_id: is_available} + """ + results = {} + + async with self.db.acquire() as conn: + for item in items: + product_id = item["product_id"] + quantity = item["quantity"] + + available = await self._get_available_quantity(conn, product_id) + results[product_id] = available >= quantity + + return results + + async def restock( + self, + product_id: int, + quantity: int, + location_id: int + ): + """Add inventory to a location.""" + async with self.db.acquire() as conn: + await conn.execute( + """INSERT INTO inventory_items (product_id, location_id, quantity_on_hand) + VALUES ($1, $2, $3) + ON CONFLICT (product_id, location_id) + DO UPDATE SET + quantity_on_hand = inventory_items.quantity_on_hand + EXCLUDED.quantity_on_hand, + last_restocked_at = NOW()""", + product_id, location_id, quantity + ) + + logger.info(f"Restocked {quantity} units of product {product_id} at location {location_id}") + + async def adjust_inventory( + self, + product_id: int, + location_id: int, + quantity: int, + reason: str = "manual_adjustment" + ): + """Manual inventory adjustment.""" + async with self.db.acquire() as conn: + await conn.execute( + """UPDATE inventory_items + SET quantity_on_hand = quantity_on_hand + $1, + updated_at = NOW() + WHERE product_id = $2 AND location_id = $3""", + quantity, product_id, location_id + ) + + # Log adjustment + await conn.execute( + """INSERT INTO inventory_adjustments + (product_id, location_id, quantity, reason) + VALUES ($1, $2, $3, $4)""", + product_id, location_id, quantity, reason + ) + + logger.info(f"Adjusted inventory for product {product_id} by {quantity}: {reason}") + + +class InsufficientInventoryError(Exception): + """Raised when insufficient inventory is available.""" + pass +``` + +**Background task for expiring reservations**: +```python +async def reservation_expiration_worker(inventory_service: InventoryReservationService): + """Background worker to expire stale reservations.""" + import asyncio + + while True: + try: + expired = await inventory_service.expire_reservations() + if expired > 0: + logger.info(f"Expired {expired} stale inventory reservations") + except Exception as e: + logger.error(f"Error in reservation expiration worker: {e}") + + await asyncio.sleep(300) # Run every 5 minutes +``` + +**Database extension for adjustments**: +```sql +-- Inventory adjustments audit table +CREATE TABLE inventory_adjustments ( + id BIGSERIAL PRIMARY KEY, + product_id BIGINT NOT NULL REFERENCES products(id), + location_id INTEGER REFERENCES inventory_locations(id), + quantity INTEGER NOT NULL, -- Can be negative + reason TEXT, + adjusted_by VARCHAR(100), + created_at TIMESTAMP NOT NULL DEFAULT NOW() +); + +CREATE INDEX idx_adjustments_product ON inventory_adjustments(product_id); +CREATE INDEX idx_adjustments_date ON inventory_adjustments(created_at DESC); +``` + +## Acceptance Criteria + +- [ ] Inventory can be reserved with SELECT FOR UPDATE +- [ ] Concurrent orders don't cause overselling +- [ ] Reservations expire after timeout +- [ ] Committed reservations deduct from inventory +- [ ] Released reservations return to available +- [ ] Availability checks are accurate +- [ ] Manual adjustments work correctly + +## Notes + +**Trade-offs**: +- Per-order vs per-item reservations: Per-item for partial fulfillment +- Immediate vs deferred commit: Deferred (on payment) for better UX + +**Performance**: +- Use connection pooling +- Consider Redis for distributed locking if needed + +**Alternatives considered**: +- Pessimistic locking: Too much contention +- Optimistic with version: Harder to implement correctly +- Saga pattern: Overkill for single-database system diff --git a/ai_coder_1/subtasks/Decomp-004-04.md b/ai_coder_1/subtasks/Decomp-004-04.md new file mode 100644 index 0000000..28da263 --- /dev/null +++ b/ai_coder_1/subtasks/Decomp-004-04.md @@ -0,0 +1,674 @@ +# Subtask: Payment Integration Module + +**Parent Task**: Decomp/004 +**Subtask ID**: Decomp-004-04 +**Dependencies**: Decomp-004-01 (Database Schema), Decomp-004-03 (Inventory Reservation) + +## Description + +Implement payment integration module supporting multiple payment providers (Stripe, PayPal, etc.). Handle payment processing, idempotency, webhooks, and refund operations. + +## Requirements + +- Support multiple payment providers +- Process one-time payments +- Handle payment methods (cards, digital wallets) +- Idempotent payment processing +- Webhook signature verification +- Refund processing +- Payment status tracking +- PCI compliance (tokenization) + +## Technical Specifications + +**Payment provider interface**: +```python +from abc import ABC, abstractmethod +from typing import Optional, Dict, Any, List +from dataclasses import dataclass +from enum import Enum +from decimal import Decimal + +class PaymentStatus(Enum): + """Payment status values.""" + PENDING = "pending" + SUCCEEDED = "succeeded" + FAILED = "failed" + REFUNDED = "refunded" + PARTIALLY_REFUNDED = "partially_refunded" + +class PaymentMethod(Enum): + """Payment method types.""" + CARD = "card" + BANK_TRANSFER = "bank_transfer" + PAYPAL = "paypal" + APPLE_PAY = "apple_pay" + GOOGLE_PAY = "google_pay" + +@dataclass +class PaymentRequest: + """Request to process a payment.""" + amount: Decimal + currency: str + payment_method: str # Tokenized payment method ID + payment_method_type: PaymentMethod + customer_id: int + order_id: int + description: str = None + metadata: Dict[str, Any] = None + idempotency_key: str = None + +@dataclass +class PaymentResult: + """Result of payment processing.""" + success: bool + transaction_id: str + status: PaymentStatus + amount: Decimal + currency: str + failure_reason: Optional[str] = None + provider_data: Dict[str, Any] = None + requires_action: bool = False + next_action: Optional[str] = None + +@dataclass +class RefundRequest: + """Request to process a refund.""" + transaction_id: str + amount: Optional[Decimal] = None # None = full refund + reason: str = None + +@dataclass +class RefundResult: + """Result of refund processing.""" + success: bool + refund_id: str + amount: Decimal + status: str + failure_reason: Optional[str] = None + +class PaymentProvider(ABC): + """Abstract base class for payment providers.""" + + @abstractmethod + async def create_payment_intent( + self, + request: PaymentRequest + ) -> PaymentResult: + """Create a payment intent.""" + pass + + @abstractmethod + async def confirm_payment( + self, + payment_intent_id: str, + payment_method: str + ) -> PaymentResult: + """Confirm a payment intent.""" + pass + + @abstractmethod + async def get_payment_status( + self, + payment_intent_id: str + ) -> PaymentResult: + """Get current payment status.""" + pass + + @abstractmethod + async def refund_payment( + self, + request: RefundRequest + ) -> RefundResult: + """Process a refund.""" + pass + + @abstractmethod + async def verify_webhook_signature( + self, + payload: bytes, + signature: str + ) -> bool: + """Verify webhook signature.""" + pass + + @abstractmethod + def parse_webhook_event(self, payload: bytes) -> Dict[str, Any]: + """Parse webhook event.""" + pass +``` + +**Stripe implementation**: +```python +import stripe +import hmac +import hashlib +import json +from typing import Dict, Any + +class StripeProvider(PaymentProvider): + """Stripe payment provider implementation.""" + + def __init__(self, api_key: str, webhook_secret: str = None): + stripe.api_key = api_key + self.webhook_secret = webhook_secret + + async def create_payment_intent(self, request: PaymentRequest) -> PaymentResult: + """Create a Stripe PaymentIntent.""" + try: + intent_params = { + "amount": int(request.amount * 100), # Convert to cents + "currency": request.currency.lower(), + "payment_method": request.payment_method, + "confirm": True, + "metadata": { + "order_id": str(request.order_id), + "customer_id": str(request.customer_id) + } + } + + if request.idempotency_key: + intent_params["idempotency_key"] = request.idempotency_key + + if request.description: + intent_params["description"] = request.description + + intent = stripe.PaymentIntent.create(**intent_params) + + return self._map_payment_result(intent) + + except stripe.error.CardError as e: + return PaymentResult( + success=False, + transaction_id=intent.id if 'intent' in locals() else None, + status=PaymentStatus.FAILED, + amount=request.amount, + currency=request.currency, + failure_reason=e.user_message, + provider_data={"error_code": e.code} + ) + except Exception as e: + return PaymentResult( + success=False, + transaction_id=None, + status=PaymentStatus.FAILED, + amount=request.amount, + currency=request.currency, + failure_reason=str(e) + ) + + async def confirm_payment( + self, + payment_intent_id: str, + payment_method: str + ) -> PaymentResult: + """Confirm a Stripe PaymentIntent.""" + try: + intent = stripe.PaymentIntent.confirm( + payment_intent_id, + payment_method=payment_method + ) + return self._map_payment_result(intent) + except stripe.error.StripeError as e: + return PaymentResult( + success=False, + transaction_id=payment_intent_id, + status=PaymentStatus.FAILED, + amount=Decimal("0"), + currency="USD", + failure_reason=str(e) + ) + + async def get_payment_status( + self, + payment_intent_id: str + ) -> PaymentResult: + """Get Stripe PaymentIntent status.""" + try: + intent = stripe.PaymentIntent.retrieve(payment_intent_id) + return self._map_payment_result(intent) + except stripe.error.StripeError as e: + return PaymentResult( + success=False, + transaction_id=payment_intent_id, + status=PaymentStatus.FAILED, + amount=Decimal("0"), + currency="USD", + failure_reason=str(e) + ) + + async def refund_payment(self, request: RefundRequest) -> RefundResult: + """Process a Stripe refund.""" + try: + refund_params = { + "payment_intent": request.transaction_id + } + + if request.amount: + refund_params["amount"] = int(request.amount * 100) + + if request.reason: + refund_params["reason"] = request.reason + + refund = stripe.Refund.create(**refund_params) + + return RefundResult( + success=refund.status == "succeeded", + refund_id=refund.id, + amount=Decimal(str(refund.amount / 100)), + status=refund.status + ) + + except stripe.error.StripeError as e: + return RefundResult( + success=False, + refund_id=None, + amount=Decimal("0"), + status="failed", + failure_reason=str(e) + ) + + async def verify_webhook_signature( + self, + payload: bytes, + signature: str + ) -> bool: + """Verify Stripe webhook signature.""" + if not self.webhook_secret: + return False + + try: + stripe.Webhook.construct_signature( + payload, + signature, + self.webhook_secret + ) + return True + except ValueError: + return False + + def parse_webhook_event(self, payload: bytes) -> Dict[str, Any]: + """Parse Stripe webhook event.""" + return json.loads(payload) + + def _map_payment_result(self, intent) -> PaymentResult: + """Map Stripe PaymentIntent to PaymentResult.""" + status_map = { + "succeeded": PaymentStatus.SUCCEEDED, + "processing": PaymentStatus.PENDING, + "requires_payment_method": PaymentStatus.FAILED, + "requires_confirmation": PaymentStatus.PENDING, + "requires_action": PaymentStatus.PENDING, + "canceled": PaymentStatus.FAILED, + } + + status = status_map.get(intent.status, PaymentStatus.PENDING) + + return PaymentResult( + success=status == PaymentStatus.SUCCEEDED, + transaction_id=intent.id, + status=status, + amount=Decimal(str(intent.amount / 100)), + currency=intent.currency.upper(), + requires_action=intent.status == "requires_action", + next_action=self._get_next_action(intent), + provider_data={ + "client_secret": intent.client_secret, + "last_payment_error": ( + intent.last_payment_error.message + if intent.last_payment_error else None + ) + } + ) + + def _get_next_action(self, intent) -> Optional[str]: + """Get next action required from PaymentIntent.""" + if intent.next_action: + if intent.next_action.type == "use_stripe_sdk": + return "stripe_sdk" + elif intent.next_action.type == "redirect_to_url": + return "redirect" + return None +``` + +**Payment service**: +```python +from datetime import datetime, timezone +import uuid +import logging + +logger = logging.getLogger(__name__) + +class PaymentService: + """Service for processing payments through multiple providers.""" + + def __init__(self, db): + self.db = db + self.providers: Dict[str, PaymentProvider] = {} + + def register_provider(self, name: str, provider: PaymentProvider): + """Register a payment provider.""" + self.providers[name] = provider + logger.info(f"Registered payment provider: {name}") + + async def create_payment( + self, + order_id: int, + amount: Decimal, + currency: str, + payment_method: str, + payment_method_type: PaymentMethod, + provider: str = "stripe", + customer_id: int = None, + idempotency_key: str = None + ) -> PaymentResult: + """Create and process a payment.""" + provider_instance = self.providers.get(provider) + if not provider_instance: + raise ValueError(f"Unknown payment provider: {provider}") + + # Generate idempotency key if not provided + if not idempotency_key: + idempotency_key = f"{order_id}_{uuid.uuid4()}" + + request = PaymentRequest( + amount=amount, + currency=currency, + payment_method=payment_method, + payment_method_type=payment_method_type, + customer_id=customer_id, + order_id=order_id, + idempotency_key=idempotency_key + ) + + # Process payment + result = await provider_instance.create_payment_intent(request) + + # Record transaction in database + await self._record_payment_transaction( + order_id=order_id, + transaction_id=result.transaction_id, + provider=provider, + payment_method=payment_method_type.value, + amount=amount, + currency=currency, + status=result.status.value, + failure_reason=result.failure_reason, + provider_data=result.provider_data + ) + + return result + + async def confirm_payment( + self, + transaction_id: str, + payment_method: str, + provider: str = "stripe" + ) -> PaymentResult: + """Confirm a pending payment.""" + provider_instance = self.providers.get(provider) + if not provider_instance: + raise ValueError(f"Unknown payment provider: {provider}") + + result = await provider_instance.confirm_payment(transaction_id, payment_method) + + # Update transaction status + await self._update_payment_status( + transaction_id, + result.status.value, + result.failure_reason + ) + + return result + + async def refund_payment( + self, + transaction_id: str, + amount: Decimal = None, + reason: str = None + ) -> RefundResult: + """Process a refund.""" + # Get transaction details + async with self.db.acquire() as conn: + transaction = await conn.fetchrow( + """SELECT * FROM payment_transactions + WHERE transaction_id = $1""", + transaction_id + ) + + if not transaction: + raise ValueError(f"Transaction not found: {transaction_id}") + + provider_name = transaction["provider"] + order_id = transaction["order_id"] + + provider_instance = self.providers.get(provider_name) + if not provider_instance: + raise ValueError(f"Unknown payment provider: {provider_name}") + + request = RefundRequest( + transaction_id=transaction_id, + amount=amount, + reason=reason + ) + + result = await provider_instance.refund_payment(request) + + # Record refund + if result.success: + await self._record_refund( + payment_transaction_id=transaction["id"], + refund_id=result.refund_id, + amount=result.amount, + reason=reason + ) + + # Update order refunded amount + await self._update_order_refund(order_id, result.amount) + + return result + + async def handle_webhook( + self, + provider: str, + payload: bytes, + signature: str + ) -> Dict[str, Any]: + """Handle payment webhook.""" + provider_instance = self.providers.get(provider) + if not provider_instance: + raise ValueError(f"Unknown payment provider: {provider}") + + # Verify signature + if not await provider_instance.verify_webhook_signature(payload, signature): + raise ValueError("Invalid webhook signature") + + # Parse event + event = provider_instance.parse_webhook_event(payload) + + # Process event + await self._process_webhook_event(provider, event) + + return {"status": "processed", "event_type": event.get("type")} + + async def _process_webhook_event(self, provider: str, event: Dict[str, Any]): + """Process a webhook event.""" + event_type = event.get("type") + data = event.get("data", {}) + + if event_type == "payment_intent.succeeded": + await self._handle_payment_succeeded(provider, data) + elif event_type == "payment_intent.payment_failed": + await self._handle_payment_failed(provider, data) + elif event_type == "charge.refunded": + await self._handle_refund_succeeded(provider, data) + + async def _handle_payment_succeeded(self, provider: str, data: Dict): + """Handle successful payment webhook.""" + intent = data.get("object", {}) + transaction_id = intent.get("id") + order_id = intent.get("metadata", {}).get("order_id") + + async with self.db.acquire() as conn: + # Update transaction status + await conn.execute( + """UPDATE payment_transactions + SET status = 'succeeded', processed_at = NOW() + WHERE transaction_id = $1""", + transaction_id + ) + + # Update order status + await conn.execute( + """UPDATE orders + SET status = 'paid', + paid_amount = paid_amount + $1, + paid_at = NOW() + WHERE id = $2""", + Decimal(str(intent.get("amount", 0))) / 100, + order_id + ) + + logger.info(f"Payment succeeded: {transaction_id} for order {order_id}") + + async def _handle_payment_failed(self, provider: str, data: Dict): + """Handle failed payment webhook.""" + intent = data.get("object", {}) + transaction_id = intent.get("id") + + async with self.db.acquire() as conn: + await conn.execute( + """UPDATE payment_transactions + SET status = 'failed', + failure_reason = $1, + processed_at = NOW() + WHERE transaction_id = $2""", + intent.get("last_payment_error", {}).get("message", "Unknown error"), + transaction_id + ) + + logger.warning(f"Payment failed: {transaction_id}") + + async def _handle_refund_succeeded(self, provider: str, data: Dict): + """Handle refund webhook.""" + charge = data.get("object", {}) + payment_intent_id = charge.get("payment_intent") + + async with self.db.acquire() as conn: + # Record refund + transaction = await conn.fetchrow( + "SELECT id, order_id FROM payment_transactions WHERE transaction_id = $1", + payment_intent_id + ) + + if transaction: + await conn.execute( + """INSERT INTO refunds + (payment_transaction_id, refund_id, amount, status, processed_at) + VALUES ($1, $2, $3, 'succeeded', NOW())""", + transaction["id"], + charge.get("id"), + Decimal(str(charge.get("amount", 0))) / 100 + ) + + # Update order + await conn.execute( + """UPDATE orders + SET refunded_amount = refunded_amount + $1 + WHERE id = $2""", + Decimal(str(charge.get("amount", 0))) / 100, + transaction["order_id"] + ) + + logger.info(f"Refund succeeded: {charge.get('id')}") + + async def _record_payment_transaction( + self, + order_id: int, + transaction_id: str, + provider: str, + payment_method: str, + amount: Decimal, + currency: str, + status: str, + failure_reason: str = None, + provider_data: Dict = None + ): + """Record payment transaction in database.""" + async with self.db.acquire() as conn: + await conn.execute( + """INSERT INTO payment_transactions + (order_id, transaction_id, provider, payment_method, + amount, currency, status, failure_reason, metadata) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)""", + order_id, transaction_id, provider, payment_method, + amount, currency, status, failure_reason, + json.dumps(provider_data) if provider_data else None + ) + + async def _update_payment_status( + self, + transaction_id: str, + status: str, + failure_reason: str = None + ): + """Update payment transaction status.""" + async with self.db.acquire() as conn: + await conn.execute( + """UPDATE payment_transactions + SET status = $1, failure_reason = $2 + WHERE transaction_id = $3""", + status, failure_reason, transaction_id + ) + + async def _record_refund( + self, + payment_transaction_id: int, + refund_id: str, + amount: Decimal, + reason: str = None + ): + """Record refund in database.""" + async with self.db.acquire() as conn: + await conn.execute( + """INSERT INTO refunds + (payment_transaction_id, refund_id, amount, reason) + VALUES ($1, $2, $3, $4)""", + payment_transaction_id, refund_id, amount, reason + ) + + async def _update_order_refund(self, order_id: int, amount: Decimal): + """Update order refund amount.""" + async with self.db.acquire() as conn: + await conn.execute( + """UPDATE orders + SET refunded_amount = refunded_amount + $1 + WHERE id = $2""", + amount, order_id + ) +``` + +## Acceptance Criteria + +- [ ] Payments can be processed through Stripe +- [ ] Payment transactions are recorded in database +- [ ] Idempotency prevents duplicate charges +- [ ] Webhook signatures are verified +- [ ] Refunds process correctly +- [ ] Order status updates on payment success +- [ ] Multiple providers can be supported + +## Notes + +**Trade-offs**: +- Synchronous vs async payment confirmation: Async for 3D Secure +- Immediate vs deferred order creation: Reserve inventory before payment + +**Security**: +- Never log full card details +- Use tokenization (Stripe.js) +- Verify all webhooks + +**Alternatives considered**: +- Build own payment processing: Rejected (PCI compliance too complex) +- Braintree vs Stripe: Stripe has better API diff --git a/ai_coder_1/subtasks/Decomp-004-05.md b/ai_coder_1/subtasks/Decomp-004-05.md new file mode 100644 index 0000000..3a64221 --- /dev/null +++ b/ai_coder_1/subtasks/Decomp-004-05.md @@ -0,0 +1,547 @@ +# Subtask: Order Workflow Engine + +**Parent Task**: Decomp/004 +**Subtask ID**: Decomp/004-05 +**Dependencies**: Decomp-004-01 (Database Schema), Decomp-004-03 (Inventory Reservation), Decomp-004-04 (Payment Integration) + +## Description + +Implement order workflow engine managing the complete order lifecycle from cart creation to delivery. Handle state transitions, inventory coordination, payment processing, and order fulfillment. + +## Requirements + +- Complete order lifecycle management +- State machine for order statuses +- Cart to order conversion +- Payment processing integration +- Inventory reservation coordination +- Order status transitions with validation +- Event-driven order updates +- Support for order modifications + +## Technical Specifications + +**Order status enum and transitions**: +```python +from enum import Enum +from typing import Dict, Set, List, Optional +from dataclasses import dataclass +from datetime import datetime, timezone +from decimal import Decimal +import logging + +logger = logging.getLogger(__name__) + +class OrderStatus(Enum): + """Order status values.""" + PENDING = "pending" # Initial state, awaiting payment + PROCESSING = "processing" # Payment received, preparing + PAID = "paid" # Payment confirmed + SHIPPED = "shipped" # Shipped to customer + DELIVERED = "delivered" # Delivered to customer + CANCELLED = "cancelled" # Cancelled by customer/system + REFUNDED = "refunded" # Refunded + +# Valid status transitions +VALID_TRANSITIONS: Dict[OrderStatus, Set[OrderStatus]] = { + OrderStatus.PENDING: { + OrderStatus.PROCESSING, # Payment initiated + OrderStatus.PAID, # Payment confirmed + OrderStatus.CANCELLED, # Cancelled before payment + }, + OrderStatus.PROCESSING: { + OrderStatus.PAID, # Payment completed + OrderStatus.CANCELLED, # Payment failed/customer cancelled + }, + OrderStatus.PAID: { + OrderStatus.SHIPPED, # Shipped + OrderStatus.REFUNDED, # Refunded + OrderStatus.CANCELLED, # Cancelled before shipping + }, + OrderStatus.SHIPPED: { + OrderStatus.DELIVERED, # Delivered + OrderStatus.REFUNDED, # Return/refund + }, + OrderStatus.DELIVERED: { + OrderStatus.REFUNDED, # Return/refund + }, + OrderStatus.CANCELLED: set(), # Terminal state + OrderStatus.REFUNDED: set(), # Terminal state +} + +@dataclass +class OrderItem: + """Item in an order.""" + product_id: int + sku: str + name: str + quantity: int + unit_price: Decimal + +@dataclass +class Order: + """Order domain object.""" + id: int + order_number: str + customer_id: int + status: OrderStatus + items: List[OrderItem] + subtotal: Decimal + tax_amount: Decimal + shipping_amount: Decimal + total_amount: Decimal + billing_address: dict + shipping_address: dict + created_at: datetime + updated_at: datetime + paid_at: Optional[datetime] = None + shipped_at: Optional[datetime] = None + delivered_at: Optional[datetime] = None + cancelled_at: Optional[datetime] = None +``` + +**Order workflow service**: +```python +class OrderWorkflowService: + """Service for managing order workflow and state transitions.""" + + def __init__( + self, + db, + inventory_service, + payment_service, + notification_service + ): + self.db = db + self.inventory = inventory_service + self.payment = payment_service + self.notifications = notification_service + + async def create_order_from_cart( + self, + cart_id: int, + customer_id: int, + billing_address: dict, + shipping_address: dict, + shipping_method: str = "standard" + ) -> Order: + """Create an order from shopping cart.""" + async with self.db.acquire() as conn: + async with conn.transaction(): + # Load cart with items + cart = await self._load_cart(conn, cart_id) + if not cart or not cart["items"]: + raise ValueError("Cannot create order from empty cart") + + # Calculate totals + subtotal = sum( + Decimal(str(item["unit_price"])) * item["quantity"] + for item in cart["items"] + ) + tax_amount = Decimal("0") # Calculate based on address + shipping_amount = await self._calculate_shipping( + cart["items"], shipping_address, shipping_method + ) + total_amount = subtotal + tax_amount + shipping_amount + + # Create order + order = await conn.fetchrow( + """INSERT INTO orders + (customer_id, status, subtotal, tax_amount, shipping_amount, + total_amount, billing_address, shipping_address, + shipping_method, payment_method) + VALUES ($1, 'pending', $2, $3, $4, $5, $6, $7, $8, 'card') + RETURNING *""", + customer_id, subtotal, tax_amount, shipping_amount, + total_amount, + json.dumps(billing_address), + json.dumps(shipping_address), + shipping_method + ) + + order_id = order["id"] + order_number = order["order_number"] + + # Copy cart items to order items + for item in cart["items"]: + await conn.execute( + """INSERT INTO order_items + (order_id, product_id, sku, product_name, quantity, + unit_price, total_amount, product_snapshot) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8)""", + order_id, + item["product_id"], + item["sku"], + item["name"], + item["quantity"], + item["unit_price"], + Decimal(str(item["unit_price"])) * item["quantity"], + item.get("product_snapshot", {}) + ) + + # Reserve inventory + reservation_result = await self.inventory.reserve_inventory( + order_id, + [ + {"product_id": item["product_id"], "quantity": item["quantity"]} + for item in cart["items"] + ] + ) + + if not reservation_result.success: + raise ValueError( + f"Insufficient inventory: {reservation_result.failed_items}" + ) + + # Clear cart + await conn.execute("DELETE FROM shopping_carts WHERE id = $1", cart_id) + + logger.info(f"Created order {order_number} for customer {customer_id}") + + # Send order confirmation + await self.notifications.send_order_confirmation(order_id) + + return await self._load_order(conn, order_id) + + async def transition_status( + self, + order_id: int, + new_status: OrderStatus, + reason: str = None, + changed_by: str = None + ) -> Order: + """Transition order to new status with validation.""" + async with self.db.acquire() as conn: + # Get current order + order = await conn.fetchrow( + "SELECT * FROM orders WHERE id = $1", + order_id + ) + + if not order: + raise ValueError(f"Order not found: {order_id}") + + current_status = OrderStatus(order["status"]) + + # Validate transition + if new_status not in VALID_TRANSITIONS.get(current_status, set()): + raise ValueError( + f"Invalid status transition: {current_status.value} -> {new_status.value}" + ) + + # Execute transition-specific logic + await self._execute_status_transition( + conn, order, current_status, new_status, reason, changed_by + ) + + # Log status change + await conn.execute( + """INSERT INTO order_status_history + (order_id, from_status, to_status, reason, changed_by) + VALUES ($1, $2, $3, $4, $5)""", + order_id, current_status.value, new_status.value, reason, changed_by + ) + + logger.info( + f"Order {order['order_number']}: {current_status.value} -> {new_status.value}" + ) + + return await self._load_order(conn, order_id) + + async def _execute_status_transition( + self, + conn, + order: dict, + current_status: OrderStatus, + new_status: OrderStatus, + reason: str, + changed_by: str + ): + """Execute logic specific to status transition.""" + + # Handle payment confirmation + if new_status == OrderStatus.PAID: + await self._handle_payment_confirmed(conn, order) + + # Handle shipping + elif new_status == OrderStatus.SHIPPED: + await self._handle_order_shipped(conn, order) + + # Handle delivery + elif new_status == OrderStatus.DELIVERED: + await self._handle_order_delivered(conn, order) + + # Handle cancellation + elif new_status == OrderStatus.CANCELLED: + await self._handle_order_cancelled(conn, order, reason) + + # Handle refund + elif new_status == OrderStatus.REFUNDED: + await self._handle_order_refunded(conn, order, reason) + + async def _handle_payment_confirmed(self, conn, order: dict): + """Handle successful payment.""" + # Commit inventory reservations + await self.inventory.commit_reservations(order["id"]) + + # Update order + await conn.execute( + """UPDATE orders + SET status = 'paid', + paid_at = NOW(), + paid_amount = total_amount + WHERE id = $1""", + order["id"] + ) + + # Send payment confirmation + await self.notifications.send_payment_confirmation(order["id"]) + + async def _handle_order_shipped(self, conn, order: dict): + """Handle order shipment.""" + await conn.execute( + """UPDATE orders + SET status = 'shipped', + shipped_at = NOW() + WHERE id = $1""", + order["id"] + ) + + # Send shipping notification + await self.notifications.send_shipping_notification(order["id"]) + + async def _handle_order_delivered(self, conn, order: dict): + """Handle order delivery.""" + await conn.execute( + """UPDATE orders + SET status = 'delivered', + actual_delivery_at = NOW() + WHERE id = $1""", + order["id"] + ) + + # Send delivery notification + await self.notifications.send_delivery_notification(order["id"]) + + async def _handle_order_cancelled(self, conn, order: dict, reason: str): + """Handle order cancellation.""" + # Release inventory reservations + await self.inventory.release_reservations(order["id"]) + + # Update order + await conn.execute( + """UPDATE orders + SET status = 'cancelled', + cancelled_at = NOW(), + cancelled_reason = $1 + WHERE id = $2""", + reason or "Customer request", + order["id"] + ) + + # Send cancellation notification + await self.notifications.send_cancellation_notification(order["id"]) + + async def _handle_order_refunded(self, conn, order: dict, reason: str): + """Handle order refund.""" + await conn.execute( + """UPDATE orders + SET status = 'refunded' + WHERE id = $1""", + order["id"] + ) + + # Send refund notification + await self.notifications.send_refund_notification(order["id"]) + + async def process_payment( + self, + order_id: int, + payment_method: str, + payment_method_type: str + ) -> dict: + """Process payment for an order.""" + async with self.db.acquire() as conn: + order = await conn.fetchrow( + "SELECT * FROM orders WHERE id = $1", + order_id + ) + + if not order: + raise ValueError(f"Order not found: {order_id}") + + if order["status"] not in ("pending", "processing"): + raise ValueError( + f"Cannot process payment for order in status: {order['status']}" + ) + + # Update to processing + await conn.execute( + "UPDATE orders SET status = 'processing' WHERE id = $1", + order_id + ) + + # Process payment + result = await self.payment.create_payment( + order_id=order_id, + amount=Decimal(str(order["total_amount"])), + currency=order["currency"], + payment_method=payment_method, + payment_method_type=PaymentMethod(payment_method_type), + customer_id=order["customer_id"] + ) + + if result.success: + # Transition to paid + await self.transition_status( + order_id, + OrderStatus.PAID, + changed_by="payment_system" + ) + else: + # Payment failed, release inventory + await self.inventory.release_reservations(order_id) + await self.transition_status( + order_id, + OrderStatus.CANCELLED, + reason=f"Payment failed: {result.failure_reason}", + changed_by="payment_system" + ) + + return { + "success": result.success, + "transaction_id": result.transaction_id, + "failure_reason": result.failure_reason, + "requires_action": result.requires_action, + "next_action": result.next_action + } + + async def get_order(self, order_id: int) -> Optional[Order]: + """Get order by ID.""" + async with self.db.acquire() as conn: + return await self._load_order(conn, order_id) + + async def get_customer_orders( + self, + customer_id: int, + limit: int = 50, + offset: int = 0 + ) -> List[Order]: + """Get orders for a customer.""" + async with self.db.acquire() as conn: + rows = await conn.fetch( + """SELECT * FROM orders + WHERE customer_id = $1 + ORDER BY created_at DESC + LIMIT $2 OFFSET $3""", + customer_id, limit, offset + ) + + return [await self._load_order(conn, row["id"]) for row in rows] + + async def _load_order(self, conn, order_id: int) -> Order: + """Load order with items.""" + order = await conn.fetchrow( + "SELECT * FROM orders WHERE id = $1", + order_id + ) + + if not order: + return None + + items = await conn.fetch( + "SELECT * FROM order_items WHERE order_id = $1", + order_id + ) + + return Order( + id=order["id"], + order_number=order["order_number"], + customer_id=order["customer_id"], + status=OrderStatus(order["status"]), + items=[ + OrderItem( + product_id=item["product_id"], + sku=item["sku"], + name=item["product_name"], + quantity=item["quantity"], + unit_price=Decimal(str(item["unit_price"])) + ) + for item in items + ], + subtotal=Decimal(str(order["subtotal"])), + tax_amount=Decimal(str(order["tax_amount"])), + shipping_amount=Decimal(str(order["shipping_amount"])), + total_amount=Decimal(str(order["total_amount"])), + billing_address=order["billing_address"], + shipping_address=order["shipping_address"], + created_at=order["created_at"], + updated_at=order["updated_at"], + paid_at=order.get("paid_at"), + shipped_at=order.get("shipped_at"), + delivered_at=order.get("actual_delivery_at"), + cancelled_at=order.get("cancelled_at") + ) + + async def _load_cart(self, conn, cart_id: int) -> Optional[dict]: + """Load cart with items.""" + cart = await conn.fetchrow( + "SELECT * FROM shopping_carts WHERE id = $1", + cart_id + ) + + if not cart: + return None + + items = await conn.fetch( + """SELECT ci.*, p.sku, p.name + FROM cart_items ci + JOIN products p ON p.id = ci.product_id + WHERE ci.cart_id = $1""", + cart_id + ) + + return { + **dict(cart), + "items": [dict(item) for item in items] + } + + async def _calculate_shipping( + self, + items: list, + address: dict, + method: str + ) -> Decimal: + """Calculate shipping cost.""" + # Simple flat rate logic + rates = { + "standard": Decimal("9.99"), + "express": Decimal("19.99"), + "overnight": Decimal("39.99") + } + return rates.get(method, rates["standard"]) +``` + +## Acceptance Criteria + +- [ ] Orders can be created from carts +- [ ] Status transitions are validated +- [ ] Inventory is reserved on order creation +- [ ] Inventory is committed on payment +- [ ] Inventory is released on cancellation +- [ ] Payment processing integrates correctly +- [ ] Notifications are sent on status changes + +## Notes + +**Trade-offs**: +- Immediate vs eventual consistency: Strong consistency for order states +- Centralized vs distributed workflow: Centralized for simplicity + +**Performance**: +- Use message queue for async notifications +- Cache order status for frequent checks + +**Alternatives considered**: +- Event sourcing: Overkill for this use case +- External workflow engine: Added complexity diff --git a/ai_coder_1/subtasks/Decomp-004-06.md b/ai_coder_1/subtasks/Decomp-004-06.md new file mode 100644 index 0000000..ed40fce --- /dev/null +++ b/ai_coder_1/subtasks/Decomp-004-06.md @@ -0,0 +1,592 @@ +# Subtask: Shipping Label Generation + +**Parent Task**: Decomp/004 +**Subtask ID**: Decomp/004-06 +**Dependencies**: Decomp-004-01 (Database Schema), Decomp-004-05 (Order Workflow Engine) + +## Description + +Implement shipping label generation supporting multiple carriers (UPS, FedEx, USPS). Handle address validation, rate calculation, label creation, and tracking integration. + +## Requirements + +- Support multiple shipping carriers (UPS, FedEx, USPS) +- Generate shipping labels (PDF) +- Calculate shipping rates +- Validate shipping addresses +- Track shipments +- Handle shipment status updates +- Support multiple service levels (ground, express, overnight) + +## Technical Specifications + +**Shipping provider interface**: +```python +from abc import ABC, abstractmethod +from typing import List, Optional, Dict, Any +from dataclasses import dataclass +from decimal import Decimal +from enum import Enum + +class ServiceLevel(Enum): + """Shipping service levels.""" + GROUND = "ground" + EXPRESS = "express" + OVERNIGHT = "overnight" + ECONOMY = "economy" + +@dataclass +class Address: + """Shipping address.""" + first_name: str + last_name: str + company: Optional[str] = None + address_line1: str = None + address_line2: Optional[str] = None + city: str = None + state_province: Optional[str] = None + postal_code: str = None + country_code: str = "US" + phone: Optional[str] = None + email: Optional[str] = None + +@dataclass +class Package: + """Package details.""" + weight_ounces: float + length_inches: float = 10 + width_inches: float = 8 + height_inches: float = 4 + description: str = "Package" + +@dataclass +class ShippingRate: + """Shipping rate quote.""" + carrier: str + service_level: ServiceLevel + amount: Decimal + currency: str = "USD" + estimated_delivery_days: int = None + +@dataclass +class ShippingLabel: + """Generated shipping label.""" + label_id: str + tracking_number: str + carrier: str + service_level: ServiceLevel + label_data: bytes # PDF bytes + cost: Decimal + estimated_delivery: str = None + +class ShippingCarrier(ABC): + """Abstract base for shipping carriers.""" + + @abstractmethod + async def validate_address(self, address: Address) -> tuple[bool, Address, str]: + """Validate and normalize address.""" + pass + + @abstractmethod + async def get_rates( + self, + from_address: Address, + to_address: Address, + packages: List[Package] + ) -> List[ShippingRate]: + """Get shipping rates.""" + pass + + @abstractmethod + async def create_label( + self, + from_address: Address, + to_address: Address, + package: Package, + service_level: ServiceLevel + ) -> ShippingLabel: + """Create shipping label.""" + pass + + @abstractmethod + async def track_shipment(self, tracking_number: str) -> Dict[str, Any]: + """Track shipment status.""" + pass + + @abstractmethod + async def cancel_label(self, label_id: str) -> bool: + """Cancel shipping label.""" + pass +``` + +**FedEx implementation**: +```python +import aiohttp +import xml.etree.ElementTree as ET +from decimal import Decimal + +class FedExCarrier(ShippingCarrier): + """FedEx shipping carrier implementation.""" + + def __init__( + self, + api_key: str, + secret_key: str, + account_number: str, + meter_number: str, + sandbox: bool = True + ): + self.api_key = api_key + self.secret_key = secret_key + self.account_number = account_number + self.meter_number = meter_number + self.sandbox = sandbox + self.base_url = ( + "https://wsbeta.fedex.com/web-service" if sandbox + else "https://ws.fedex.com/web-service" + ) + + async def validate_address(self, address: Address) -> tuple[bool, Address, str]: + """Validate address via FedEx API.""" + # Implementation would call FedEx Address Validation Service + # For now, return as-is + return True, address, None + + async def get_rates( + self, + from_address: Address, + to_address: Address, + packages: List[Package] + ) -> List[ShippingRate]: + """Get FedEx shipping rates.""" + # Implementation would call FedEx Rate Service + # Return sample rates for now + total_weight = sum(p.weight_ounces for p in packages) / 16 # Convert to lbs + + rates = [ + ShippingRate( + carrier="fedex", + service_level=ServiceLevel.GROUND, + amount=Decimal(str(max(8.99, total_weight * 1.5))), + estimated_delivery_days=5 + ), + ShippingRate( + carrier="fedex", + service_level=ServiceLevel.EXPRESS, + amount=Decimal(str(max(19.99, total_weight * 3))), + estimated_delivery_days=2 + ), + ShippingRate( + carrier="fedex", + service_level=ServiceLevel.OVERNIGHT, + amount=Decimal(str(max(39.99, total_weight * 5))), + estimated_delivery_days=1 + ) + ] + + return rates + + async def create_label( + self, + from_address: Address, + to_address: Address, + package: Package, + service_level: ServiceLevel + ) -> ShippingLabel: + """Create FedEx shipping label.""" + # Implementation would call FedEx Ship Service + # Generate a mock tracking number and label for now + import uuid + tracking_num = f"1FD{str(uuid.uuid4()).upper()[:12]}" + label_id = str(uuid.uuid4()) + + # Get rate for this service + rates = await self.get_rates(from_address, to_address, [package]) + rate = next((r for r in rates if r.service_level == service_level), rates[0]) + + # Generate PDF label (mock) + label_data = self._generate_label_pdf( + tracking_num, from_address, to_address, service_level + ) + + return ShippingLabel( + label_id=label_id, + tracking_number=tracking_num, + carrier="fedex", + service_level=service_level, + label_data=label_data, + cost=rate.amount, + estimated_delivery=f"{rate.estimated_delivery_days} business days" + ) + + async def track_shipment(self, tracking_number: str) -> Dict[str, Any]: + """Track FedEx shipment.""" + # Implementation would call FedEx Tracking Service + return { + "tracking_number": tracking_number, + "status": "in_transit", + "estimated_delivery": "2024-01-20", + "events": [ + { + "date": "2024-01-18T10:00:00Z", + "status": "picked_up", + "location": "Memphis, TN", + "description": "Package picked up" + }, + { + "date": "2024-01-18T15:30:00Z", + "status": "in_transit", + "location": "Memphis, TN", + "description": "Departed FedEx facility" + } + ] + } + + async def cancel_label(self, label_id: str) -> bool: + """Cancel FedEx label.""" + # Implementation would call FedEx Cancellation Service + return True + + def _generate_label_pdf( + self, + tracking_number: str, + from_addr: Address, + to_addr: Address, + service: ServiceLevel + ) -> bytes: + """Generate PDF label (mock).""" + # In production, this would use reportlab or carrier-provided PDF + import io + + # Mock PDF data + pdf_content = f"""SHIPPING LABEL +================ +Carrier: FedEx +Service: {service.value.upper()} +Tracking: {tracking_number} + +FROM: +{from_addr.first_name} {from_addr.last_name} +{from_addr.address_line1} +{from_addr.city}, {from_addr.state_province} {from_addr.postal_code} + +TO: +{to_addr.first_name} {to_addr.last_name} +{to_addr.address_line1} +{to_addr.city}, {to_addr.state_province} {to_addr.postal_code} + +|| BARCODE: {tracking_number} || +================""" + + return pdf_content.encode('utf-8') +``` + +**Shipping service**: +```python +from datetime import datetime, timezone +import logging + +logger = logging.getLogger(__name__) + +class ShippingService: + """Service for shipping operations.""" + + def __init__(self, db): + self.db = db + self.carriers: Dict[str, ShippingCarrier] = {} + self.default_from_address: Address = None + + def register_carrier(self, name: str, carrier: ShippingCarrier): + """Register a shipping carrier.""" + self.carriers[name] = carrier + logger.info(f"Registered shipping carrier: {name}") + + def set_from_address(self, address: Address): + """Set default ship-from address.""" + self.default_from_address = address + + async def get_shipping_rates( + self, + order_id: int + ) -> List[ShippingRate]: + """Get shipping rates for an order.""" + async with self.db.acquire() as conn: + order = await conn.fetchrow( + """SELECT o.*, jsonb_array_elements(o.order_items) as item_data + FROM orders o + WHERE o.id = $1""", + order_id + ) + + if not order: + raise ValueError(f"Order not found: {order_id}") + + to_address = Address(**order["shipping_address"]) + packages = await self._create_packages_from_order(order) + + all_rates = [] + for carrier in self.carriers.values(): + try: + rates = await carrier.get_rates( + self.default_from_address, + to_address, + packages + ) + all_rates.extend(rates) + except Exception as e: + logger.error(f"Error getting rates from carrier: {e}") + + # Sort by price + all_rates.sort(key=lambda r: r.amount) + return all_rates + + async def create_shipping_label( + self, + order_id: int, + carrier: str, + service_level: ServiceLevel + ) -> ShippingLabel: + """Create shipping label for an order.""" + carrier_instance = self.carriers.get(carrier) + if not carrier_instance: + raise ValueError(f"Unknown carrier: {carrier}") + + async with self.db.acquire() as conn: + order = await conn.fetchrow( + "SELECT * FROM orders WHERE id = $1", + order_id + ) + + if not order: + raise ValueError(f"Order not found: {order_id}") + + if order["status"] != "paid": + raise ValueError(f"Order must be paid before shipping") + + to_address = Address(**order["shipping_address"]) + packages = await self._create_packages_from_order(order) + + # Create label + label = await carrier_instance.create_label( + self.default_from_address, + to_address, + packages[0], # Use first package + service_level + ) + + # Save to database + async with self.db.acquire() as conn: + await conn.execute( + """INSERT INTO shipping_labels + (order_id, label_id, provider, service_level, tracking_number, + shipment_cost, label_data, from_address, to_address, package_details) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)""", + order_id, + label.label_id, + carrier, + service_level.value, + label.tracking_number, + label.cost, + label.label_data, + self._address_to_dict(self.default_from_address), + self._address_to_dict(to_address), + {"weight_ounces": packages[0].weight_ounces} + ) + + # Update order + await conn.execute( + """UPDATE orders + SET tracking_number = $2, + shipping_carrier = $3, + shipping_method = $4 + WHERE id = $1""", + order_id, + label.tracking_number, + carrier, + service_level.value + ) + + logger.info(f"Created shipping label {label.label_id} for order {order_id}") + return label + + async def track_shipment(self, tracking_number: str, carrier: str = None) -> Dict[str, Any]: + """Track a shipment.""" + if carrier: + carrier_instance = self.carriers.get(carrier) + else: + # Find carrier from tracking number format + carrier_instance = self._identify_carrier(tracking_number) + + if not carrier_instance: + raise ValueError(f"Cannot identify carrier for tracking: {tracking_number}") + + tracking_info = await carrier_instance.track_shipment(tracking_number) + + # Update tracking in database if order exists + async with self.db.acquire() as conn: + await conn.execute( + """UPDATE shipping_labels + SET status = $1 + WHERE tracking_number = $2""", + tracking_info["status"], + tracking_number + ) + + return tracking_info + + async def update_tracking_status(self): + """ + Background task to update tracking status for all shipments. + + Should be run periodically (e.g., every 30 minutes). + """ + async with self.db.acquire() as conn: + # Get all in-transit shipments + shipments = await conn.fetch( + """SELECT tracking_number, provider + FROM shipping_labels + WHERE status IN ('created', 'shipped') + ORDER BY created_at DESC""" + ) + + updated = 0 + for shipment in shipments: + try: + tracking = await self.track_shipment( + shipment["tracking_number"], + shipment["provider"] + ) + updated += 1 + except Exception as e: + logger.error(f"Error updating tracking for {shipment['tracking_number']}: {e}") + + logger.info(f"Updated tracking for {updated} shipments") + return updated + + async def _create_packages_from_order(self, order: dict) -> List[Package]: + """Create package list from order.""" + # Simple logic: one package containing all items + total_weight = 0 + + items = await self.db.fetch( + "SELECT * FROM order_items WHERE order_id = $1", + order["id"] + ) + + for item in items: + # Get product weight + product = await self.db.fetchrow( + "SELECT weight_grams FROM products WHERE id = $1", + item["product_id"] + ) + if product: + weight_per_unit = (product["weight_grams"] or 100) / 28.35 # Convert to oz + total_weight += weight_per_unit * item["quantity"] + + return [ + Package( + weight_ounces=max(1, total_weight), + description=f"Order {order['order_number']}" + ) + ] + + def _address_to_dict(self, address: Address) -> dict: + """Convert Address to dict.""" + return { + "first_name": address.first_name, + "last_name": address.last_name, + "company": address.company, + "address_line1": address.address_line1, + "address_line2": address.address_line2, + "city": address.city, + "state_province": address.state_province, + "postal_code": address.postal_code, + "country_code": address.country_code, + "phone": address.phone + } + + def _identify_carrier(self, tracking_number: str) -> Optional[ShippingCarrier]: + """Identify carrier from tracking number format.""" + if tracking_number.startswith("1Z"): + return self.carriers.get("ups") + elif tracking_number.startswith("1FD") or tracking_number.startswith("96"): + return self.carriers.get("fedex") + elif tracking_number.isdigit() and len(tracking_number) >= 18: + return self.carriers.get("usps") + return None + + async def get_label_pdf(self, label_id: str) -> bytes: + """Get label PDF data.""" + async with self.db.acquire() as conn: + row = await conn.fetchrow( + "SELECT label_data FROM shipping_labels WHERE label_id = $1", + label_id + ) + + if not row: + raise ValueError(f"Label not found: {label_id}") + + return row["label_data"] +``` + +**Tracking webhook handler**: +```python +async def handle_tracking_webhook( + carrier: str, + payload: dict, + shipping_service: ShippingService +): + """Handle tracking update webhook from carrier.""" + tracking_number = payload.get("tracking_number") + status = payload.get("status") + timestamp = payload.get("timestamp") + + if not tracking_number: + return {"error": "Missing tracking_number"} + + async with shipping_service.db.acquire() as conn: + # Update label status + await conn.execute( + """UPDATE shipping_labels + SET status = $1 + WHERE tracking_number = $2""", + status, + tracking_number + ) + + # Check if delivered, update order + if status == "delivered": + await conn.execute( + """UPDATE orders + SET status = 'delivered', + actual_delivery_at = $1 + WHERE tracking_number = $2""", + timestamp or datetime.now(timezone.utc), + tracking_number + ) + + return {"status": "updated"} +``` + +## Acceptance Criteria + +- [ ] Shipping rates can be calculated +- [ ] Labels can be generated for carriers +- [ ] Tracking numbers are stored +- [ ] Tracking status updates work +- [ ] Labels can be retrieved as PDF +- [ ] Order status updates on delivery + +## Notes + +**Trade-offs**: +- Generate vs carrier-provided labels: Carrier API preferred +- Real-time vs batch tracking updates: Batch for efficiency + +**Performance**: +- Cache rates for same address/weight combo +- Queue tracking updates + +**Alternatives considered**: +- EasyPost/Shippo: Simplifies multi-carrier integration +- Direct carrier APIs: More control but more complex diff --git a/ai_coder_1/subtasks/Decomp-004-07.md b/ai_coder_1/subtasks/Decomp-004-07.md new file mode 100644 index 0000000..c9a40d8 --- /dev/null +++ b/ai_coder_1/subtasks/Decomp-004-07.md @@ -0,0 +1,613 @@ +# Subtask: Order Cancellation and Refunds + +**Parent Task**: Decomp/004 +**Subtask ID**: Decomp-004-07 +**Dependencies**: Decomp-004-03 (Inventory Reservation), Decomp-004-04 (Payment Integration), Decomp-004-05 (Order Workflow Engine) + +## Description + +Implement order cancellation and refund handling. Support cancellation at different order stages, automatic refund processing, return management, and partial refunds. + +## Requirements + +- Cancel orders at different stages +- Release inventory on cancellation +- Process refunds via payment provider +- Handle partial refunds +- Support returns and exchanges +- Track refund status +- Cancellation restrictions based on order status +- Refund reason tracking + +## Technical Specifications + +**Cancellation policy**: +```python +from enum import Enum +from typing import Optional, List +from dataclasses import dataclass +from decimal import Decimal +from datetime import datetime, timezone + +class CancellationEligibility(Enum): + """Can order be cancelled?""" + ELIGIBLE = "eligible" + ALREADY_SHIPPED = "already_shipped" + ALREADY_DELIVERED = "already_delivered" + ALREADY_CANCELLED = "already_cancelled" + ALREADY_REFUNDED = "already_refunded" + TOO_LATE = "too_late" # e.g., >24 hours after placement + +@dataclass +class CancellationResult: + """Result of cancellation attempt.""" + success: bool + eligibility: CancellationEligibility + message: str + refund_status: Optional[str] = None + refund_amount: Optional[Decimal] = None + +@dataclass +class RefundRequest: + """Refund request details.""" + order_id: int + amount: Optional[Decimal] = None # None = full refund + reason: str = None + item_ids: Optional[List[int]] = None # For partial refunds + restock_items: bool = True +``` + +**Cancellation service**: +```python +class CancellationService: + """Service for handling order cancellations.""" + + def __init__( + self, + db, + inventory_service, + payment_service, + order_workflow + ): + self.db = db + self.inventory = inventory_service + self.payment = payment_service + self.workflow = order_workflow + + async def check_cancellation_eligibility( + self, + order_id: int + ) -> CancellationEligibility: + """Check if order can be cancelled.""" + async with self.db.acquire() as conn: + order = await conn.fetchrow( + """SELECT * FROM orders WHERE id = $1""", + order_id + ) + + if not order: + raise ValueError(f"Order not found: {order_id}") + + status = order["status"] + + # Already in terminal state + if status == "cancelled": + return CancellationEligibility.ALREADY_CANCELLED + if status == "refunded": + return CancellationEligibility.ALREADY_REFUNDED + if status == "shipped": + return CancellationEligibility.ALREADY_SHIPPED + if status == "delivered": + return CancellationEligibility.ALREADY_DELIVERED + + # Check time limit (e.g., 24 hours for paid orders) + if status in ("paid", "processing"): + hours_since_paid = ( + datetime.now(timezone.utc) - order.get("paid_at", order["created_at"]) + ).total_seconds() / 3600 + + if hours_since_paid > 24: + return CancellationEligibility.TOO_LATE + + return CancellationEligibility.ELIGIBLE + + async def cancel_order( + self, + order_id: int, + customer_id: int, + reason: str = None, + refund: bool = True + ) -> CancellationResult: + """ + Cancel an order. + + Args: + order_id: Order to cancel + customer_id: Customer requesting cancellation (for verification) + reason: Reason for cancellation + refund: Whether to process refund + + Returns: + CancellationResult with details + """ + # Verify ownership + async with self.db.acquire() as conn: + order = await conn.fetchrow( + """SELECT * FROM orders WHERE id = $1""", + order_id + ) + + if not order: + return CancellationResult( + success=False, + eligibility=CancellationEligibility.ELIGIBLE, + message="Order not found" + ) + + if order["customer_id"] != customer_id: + return CancellationResult( + success=False, + eligibility=CancellationEligibility.ELIGIBLE, + message="Not authorized to cancel this order" + ) + + # Check eligibility + eligibility = await self.check_cancellation_eligibility(order_id) + + if eligibility != CancellationEligibility.ELIGIBLE: + return CancellationResult( + success=False, + eligibility=eligibility, + message=f"Cannot cancel: {eligibility.value}" + ) + + # Process cancellation + try: + # Release inventory + await self.inventory.release_reservations(order_id) + + # Cancel shipping label if created + await self._cancel_shipping_label(order_id) + + # Process refund if requested and payment was made + refund_status = None + refund_amount = None + + if refund and order.get("paid_amount", 0) > 0: + refund_result = await self._refund_order(order_id, reason) + refund_status = refund_result.get("status") + refund_amount = refund_result.get("amount") + else: + # Just cancel without refund + await self.workflow.transition_status( + order_id, + OrderStatus.CANCELLED, + reason=reason or "Customer request", + changed_by="customer" + ) + + return CancellationResult( + success=True, + eligibility=CancellationEligibility.ELIGIBLE, + message="Order cancelled successfully", + refund_status=refund_status, + refund_amount=refund_amount + ) + + except Exception as e: + logger.error(f"Error cancelling order {order_id}: {e}") + return CancellationResult( + success=False, + eligibility=CancellationEligibility.ELIGIBLE, + message=f"Cancellation failed: {str(e)}" + ) + + async def _refund_order( + self, + order_id: int, + reason: str = None + ) -> dict: + """Process refund for order.""" + async with self.db.acquire() as conn: + # Get payment transaction + transaction = await conn.fetchrow( + """SELECT * FROM payment_transactions + WHERE order_id = $1 + AND status = 'succeeded' + ORDER BY created_at DESC + LIMIT 1""", + order_id + ) + + if not transaction: + return {"status": "no_payment_to_refund", "amount": None} + + # Get order + order = await conn.fetchrow( + "SELECT * FROM orders WHERE id = $1", + order_id + ) + + # Calculate refund amount (total - already refunded) + refund_amount = Decimal(str(order["total_amount"])) - Decimal(str(order.get("refunded_amount", 0))) + + if refund_amount <= 0: + return {"status": "already_refunded", "amount": None} + + # Process refund via payment service + try: + refund_result = await self.payment.refund_payment( + transaction_id=transaction["transaction_id"], + amount=refund_amount, + reason=reason or "Customer cancellation" + ) + + if refund_result.success: + # Update order status + await conn.execute( + """UPDATE orders + SET status = 'refunded', + refunded_amount = refunded_amount + $1 + WHERE id = $2""", + refund_result.amount, + order_id + ) + + # Log status change + await conn.execute( + """INSERT INTO order_status_history + (order_id, from_status, to_status, reason, changed_by) + VALUES ($1, $2, 'refunded', $3, 'system')""", + order_id, order["status"], reason + ) + + return { + "status": "succeeded", + "amount": refund_result.amount + } + else: + return { + "status": "failed", + "amount": None, + "error": refund_result.failure_reason + } + + except Exception as e: + logger.error(f"Refund failed for order {order_id}: {e}") + return { + "status": "failed", + "amount": None, + "error": str(e) + } + + async def _cancel_shipping_label(self, order_id: int): + """Cancel shipping label if created.""" + async with self.db.acquire() as conn: + label = await conn.fetchrow( + """SELECT * FROM shipping_labels + WHERE order_id = $1 AND status = 'created'""", + order_id + ) + + if label: + # Call carrier to cancel + # This would use the shipping service + await conn.execute( + """UPDATE shipping_labels + SET status = 'cancelled' + WHERE id = $1""", + label["id"] + ) + logger.info(f"Cancelled shipping label {label['label_id']}") +``` + +**Return and refund service**: +```python +class ReturnService: + """Service for handling returns and exchanges.""" + + def __init__(self, db, inventory_service, payment_service): + self.db = db + self.inventory = inventory_service + self.payment = payment_service + + async def create_return_request( + self, + order_id: int, + item_ids: List[int], + reason: str, + return_type: str = "refund" # refund, exchange + ) -> int: + """Create a return request.""" + async with self.db.acquire() as conn: + # Validate items belong to order + items = await conn.fetch( + """SELECT oi.*, p.name + FROM order_items oi + JOIN products p ON p.id = oi.product_id + WHERE oi.id = ANY($1) AND oi.order_id = $2""", + item_ids, + order_id + ) + + if len(items) != len(item_ids): + raise ValueError("Some items don't belong to this order") + + # Calculate return amount + return_amount = sum(Decimal(str(item["total_amount"])) for item in items) + + # Create return record + return_id = await conn.fetchval( + """INSERT INTO returns + (order_id, items, reason, return_type, return_amount, status) + VALUES ($1, $2, $3, $4, $5, 'pending') + RETURNING id""", + order_id, + json.dumps([dict(item) for item in items]), + reason, + return_type, + return_amount + ) + + logger.info(f"Created return request {return_id} for order {order_id}") + return return_id + + async def process_return( + self, + return_id: int, + approved: bool, + notes: str = None + ) -> dict: + """Process a return request.""" + async with self.db.acquire() as conn: + return_request = await conn.fetchrow( + """SELECT * FROM returns WHERE id = $1""", + return_id + ) + + if not return_request: + raise ValueError(f"Return request not found: {return_id}") + + if return_request["status"] != "pending": + raise ValueError(f"Return already processed: {return_request['status']}") + + if approved: + # Update return status + await conn.execute( + """UPDATE returns + SET status = 'approved', + processed_at = NOW(), + notes = COALESCE(notes || '; ', '') || $1 + WHERE id = $2""", + notes or "", + return_id + ) + + items = json.loads(return_request["items"]) + + if return_request["return_type"] == "refund": + # Process refund + order_id = return_request["order_id"] + transaction = await conn.fetchrow( + """SELECT pt.* FROM payment_transactions pt + JOIN orders o ON o.id = pt.order_id + WHERE o.id = $1 AND pt.status = 'succeeded' + ORDER BY pt.created_at DESC + LIMIT 1""", + order_id + ) + + if transaction: + refund_result = await self.payment.refund_payment( + transaction_id=transaction["transaction_id"], + amount=Decimal(str(return_request["return_amount"])), + reason=f"Return: {return_request['reason']}" + ) + + if refund_result.success: + # Restock items + for item in items: + await self.inventory.restock( + product_id=item["product_id"], + quantity=item["quantity"], + location_id=1 # Default location + ) + + return { + "success": True, + "refund_amount": refund_result.amount, + "message": "Return processed and refund initiated" + } + else: + return { + "success": False, + "message": f"Refund failed: {refund_result.failure_reason}" + } + + else: # exchange + # Create exchange order + await conn.execute( + """UPDATE returns + SET status = 'exchanged', + exchange_order_id = NULL + WHERE id = $1""", + return_id + ) + + return { + "success": True, + "message": "Exchange request processed" + } + else: + # Reject return + await conn.execute( + """UPDATE returns + SET status = 'rejected', + processed_at = NOW(), + notes = COALESCE(notes || '; ', '') || $1 + WHERE id = $2""", + notes or "Return request denied", + return_id + ) + + return { + "success": False, + "message": "Return request rejected" + } + + async def get_return_requests( + self, + order_id: int = None, + status: str = None + ) -> List[dict]: + """Get return requests.""" + async with self.db.acquire() as conn: + query = "SELECT * FROM returns WHERE 1=1" + params = [] + + if order_id: + query += " AND order_id = $1" + params.append(order_id) + + if status: + query += f" AND status = ${len(params) + 1}" + params.append(status) + + query += " ORDER BY created_at DESC" + + rows = await conn.fetch(query, *params) + return [dict(row) for row in rows] +``` + +**Database extension for returns**: +```sql +-- Returns table +CREATE TABLE returns ( + id BIGSERIAL PRIMARY KEY, + order_id BIGINT NOT NULL REFERENCES orders(id), + items JSONB NOT NULL, -- Array of order items being returned + reason TEXT NOT NULL, + return_type VARCHAR(20) NOT NULL, -- 'refund' or 'exchange' + return_amount DECIMAL(10, 2) NOT NULL, + status VARCHAR(20) NOT NULL DEFAULT 'pending', + -- pending, approved, rejected, exchanged, refunded + notes TEXT, + processed_at TIMESTAMP, + created_at TIMESTAMP NOT NULL DEFAULT NOW(), + exchange_order_id BIGINT REFERENCES orders(id), + refund_id BIGINT REFERENCES refunds(id), + metadata JSONB DEFAULT '{}'::jsonb +); + +CREATE INDEX idx_returns_order ON returns(order_id); +CREATE INDEX idx_returns_status ON returns(status); +``` + +**Admin API for cancellations**: +```python +from fastapi import APIRouter, Depends, HTTPException + +router = APIRouter(prefix="/admin/orders", tags=["admin-orders"]) + +@router.post("/{order_id}/cancel") +async def admin_cancel_order( + order_id: int, + reason: str = None, + force: bool = False, + refund: bool = True +): + """Admin endpoint to cancel an order.""" + cancellation_service = get_cancellation_service() + + if force: + # Force cancel even if normally ineligible + # Still releases inventory and processes refund + async with cancellation_service.db.acquire() as conn: + order = await conn.fetchrow( + "SELECT * FROM orders WHERE id = $1", + order_id + ) + + if not order: + raise HTTPException(status_code=404, detail="Order not found") + + # Release inventory + await cancellation_service.inventory.release_reservations(order_id) + + # Process refund if needed + if refund and order.get("paid_amount", 0) > 0: + refund_result = await cancellation_service._refund_order(order_id, reason) + else: + await cancellation_service.workflow.transition_status( + order_id, + OrderStatus.CANCELLED, + reason=reason or "Cancelled by admin", + changed_by="admin" + ) + refund_result = None + + return { + "success": True, + "order_id": order_id, + "refund": refund_result + } + else: + # Normal cancellation flow + result = await cancellation_service.cancel_order( + order_id, + customer_id=None, # Admin can cancel any order + reason=reason or "Cancelled by admin", + refund=refund + ) + + if not result.success: + raise HTTPException(status_code=400, detail=result.message) + + return { + "success": True, + "order_id": order_id, + "cancellation": result + } + +@router.get("/returns/pending") +async def get_pending_returns(): + """Get pending return requests.""" + return_service = get_return_service() + returns = await return_service.get_return_requests(status="pending") + return {"returns": returns} + +@router.post("/returns/{return_id}/process") +async def process_return_request( + return_id: int, + approved: bool, + notes: str = None +): + """Process a return request.""" + return_service = get_return_service() + result = await return_service.process_return(return_id, approved, notes) + return result +``` + +## Acceptance Criteria + +- [ ] Orders can be cancelled when eligible +- [ ] Cancellation eligibility is enforced +- [ ] Inventory is released on cancellation +- [ ] Refunds process correctly +- [ ] Return requests can be created +- [ ] Returns can be approved/rejected +- [ ] Admin can force cancel orders + +## Notes + +**Trade-offs**: +- Strict vs lenient cancellation policy: Configurable via settings +- Immediate vs scheduled refund: Immediate for customer satisfaction + +**Performance**: +- Queue refund processing for high volume +- Cache cancellation rules + +**Alternatives considered**: +- Third-party returns service (Returnly): Overkill for MVP +- RMA system complexity: Keep simple for now diff --git a/ai_coder_1/subtasks/Decomp-004-08.md b/ai_coder_1/subtasks/Decomp-004-08.md new file mode 100644 index 0000000..2e2e620 --- /dev/null +++ b/ai_coder_1/subtasks/Decomp-004-08.md @@ -0,0 +1,638 @@ +# Subtask: Notification System + +**Parent Task**: Decomp/004 +**Subtask ID**: Decomp/004-08 +**Dependencies**: Decomp-004-01 (Database Schema), Decomp-004-05 (Order Workflow Engine) + +## Description + +Implement notification system for order-related events. Support email, SMS, and push notifications. Handle templates, delivery tracking, and retry logic for failed notifications. + +## Requirements + +- Email notifications for order events +- SMS notifications for shipping/delivery +- Template-based message generation +- Notification delivery tracking +- Retry logic for failed notifications +- Unsubscribe handling +- Multi-language support +- Webhook notifications for external systems + +## Technical Specifications + +**Notification service**: +```python +from abc import ABC, abstractmethod +from typing import List, Optional, Dict, Any +from dataclasses import dataclass +from enum import Enum +import logging +import asyncio +from datetime import datetime, timezone, timedelta + +logger = logging.getLogger(__name__) + +class NotificationType(Enum): + """Types of notifications.""" + EMAIL = "email" + SMS = "sms" + PUSH = "push" + WEBHOOK = "webhook" + +class NotificationStatus(Enum): + """Notification delivery status.""" + PENDING = "pending" + SENT = "sent" + FAILED = "failed" + BOUNCED = "bounced" + +class NotificationEvent(Enum): + """Order-related events that trigger notifications.""" + ORDER_CREATED = "order_created" + ORDER_CONFIRMED = "order_confirmed" + PAYMENT_RECEIVED = "payment_received" + PAYMENT_FAILED = "payment_failed" + ORDER_SHIPPED = "order_shipped" + ORDER_DELIVERED = "order_delivered" + ORDER_CANCELLED = "order_cancelled" + REFUND_PROCESSED = "refund_processed" + +@dataclass +class NotificationMessage: + """Notification message.""" + recipient: str # Email or phone + type: NotificationType + subject: str = None + body: str = None + template: str = None + variables: Dict[str, Any] = None + metadata: Dict[str, Any] = None + +@dataclass +class NotificationResult: + """Result of notification send.""" + success: bool + notification_id: int = None + error: str = None + +class NotificationChannel(ABC): + """Abstract base for notification channels.""" + + @abstractmethod + async def send(self, message: NotificationMessage) -> NotificationResult: + """Send notification.""" + pass + + @abstractmethod + def validate_recipient(self, recipient: str) -> bool: + """Validate recipient address.""" + pass +``` + +**Email channel implementation**: +```python +import aiosmtplib +from email.message import EmailMessage +from string import Template + +class EmailChannel(NotificationChannel): + """Email notification channel.""" + + def __init__( + self, + smtp_host: str, + smtp_port: int, + username: str, + password: str, + from_email: str, + from_name: str = None + ): + self.smtp_host = smtp_host + self.smtp_port = smtp_port + self.username = username + self.password = password + self.from_email = from_email + self.from_name = from_name or "Store" + self.templates = self._load_templates() + + def _load_templates(self) -> Dict[str, Template]: + """Load email templates.""" + return { + "order_confirmation": Template(self._get_template("order_confirmation")), + "payment_received": Template(self._get_template("payment_received")), + "order_shipped": Template(self._get_template("order_shipped")), + "order_delivered": Template(self._get_template("order_delivered")), + "order_cancelled": Template(self._get_template("order_cancelled")), + "refund_processed": Template(self._get_template("refund_processed")), + } + + def _get_template(self, name: str) -> str: + """Get template content (in production, load from files).""" + templates = { + "order_confirmation": """ +Subject: Order Confirmation - Order #$order_number + +Dear $customer_name, + +Thank you for your order! + +Order: #$order_number +Total: $total_amount + +We'll send another email when your order ships. + +Thank you for shopping with us! +""", + "payment_received": """ +Subject: Payment Confirmation - Order #$order_number + +Dear $customer_name, + +Your payment of $amount has been received for order #$order_number. + +Your order is being prepared for shipment. +""", + "order_shipped": """ +Subject: Your Order Has Shipped - Order #$order_number + +Dear $customer_name, + +Good news! Your order has shipped. + +Tracking Number: $tracking_number +Carrier: $carrier + +Estimated Delivery: $estimated_delivery + +Track your package: $tracking_url +""", + "order_delivered": """ +Subject: Order Delivered - Order #$order_number + +Dear $customer_name, + +Your order has been delivered! + +We hope you enjoy your purchase. If you have any issues, please contact us. +""", + "order_cancelled": """ +Subject: Order Cancelled - Order #$order_number + +Dear $customer_name, + +Your order #$order_number has been cancelled. + +If you paid, a refund will be processed to your original payment method. + +Reason: $reason +""", + "refund_processed": """ +Subject: Refund Processed - Order #$order_number + +Dear $customer_name, + +A refund of $amount has been processed for order #$order_number. + +The refund should appear on your statement within 3-5 business days. +""" + } + return templates.get(name, "") + + async def send(self, message: NotificationMessage) -> NotificationResult: + """Send email notification.""" + try: + # Generate content from template + if message.template and message.variables: + template = self.templates.get(message.template) + if template: + content = template.safe_substitute(**message.variables) + # Parse subject and body + lines = content.strip().split('\n') + subject = next((l[8:] for l in lines if l.startswith('Subject:')), message.subject or "Notification") + body = '\n'.join(l for l in lines if not l.startswith('Subject:')) + else: + subject = message.subject or "Notification" + body = message.body or "" + else: + subject = message.subject or "Notification" + body = message.body or "" + + # Create email message + email_msg = EmailMessage() + email_msg["From"] = f"{self.from_name} <{self.from_email}>" + email_msg["To"] = message.recipient + email_msg["Subject"] = subject + email_msg.set_content(body) + + # Send via SMTP + async with aiosmtplib.SMTP( + hostname=self.smtp_host, + port=self.smtp_port, + use_tls=True + ) as smtp: + await smtp.login(self.username, self.password) + await smtp.send_message(email_msg) + + logger.info(f"Email sent to {message.recipient}") + return NotificationResult(success=True) + + except Exception as e: + logger.error(f"Failed to send email to {message.recipient}: {e}") + return NotificationResult( + success=False, + error=str(e) + ) + + def validate_recipient(self, recipient: str) -> bool: + """Validate email address.""" + import re + pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$' + return re.match(pattern, recipient) is not None +``` + +**SMS channel implementation**: +```python +import httpx + +class SMSChannel(NotificationChannel): + """SMS notification channel (e.g., Twilio).""" + + def __init__( + self, + account_sid: str, + auth_token: str, + from_number: str + ): + self.account_sid = account_sid + self.auth_token = auth_token + self.from_number = from_number + self.base_url = f"https://api.twilio.com/2010-04-01/Accounts/{account_sid}" + + async def send(self, message: NotificationMessage) -> NotificationResult: + """Send SMS notification.""" + try: + # For production, use Twilio SDK + async with httpx.AsyncClient() as client: + response = await client.post( + f"{self.base_url}/Messages.json", + auth=(self.account_sid, self.auth_token), + data={ + "From": self.from_number, + "To": message.recipient, + "Body": message.body or self._get_sms_body(message) + }, + timeout=10.0 + ) + response.raise_for_status() + + logger.info(f"SMS sent to {message.recipient}") + return NotificationResult(success=True) + + except Exception as e: + logger.error(f"Failed to send SMS to {message.recipient}: {e}") + return NotificationResult( + success=False, + error=str(e) + ) + + def _get_sms_body(self, message: NotificationMessage) -> str: + """Generate SMS body from template/variables.""" + if message.variables: + order_number = message.variables.get("order_number", "") + if message.template == "order_shipped": + tracking = message.variables.get("tracking_number", "") + return f"Order #{order_number} has shipped! Track: {tracking}" + elif message.template == "order_delivered": + return f"Order #{order_number} has been delivered. Thank you!" + elif message.template == "order_cancelled": + return f"Order #{order_number} has been cancelled." + + return message.body or "Update on your order" + + def validate_recipient(self, recipient: str) -> bool: + """Validate phone number.""" + # Basic validation - should be E.164 format + return recipient.startswith("+") and len(recipient) >= 10 +``` + +**Webhook channel**: +```python +import httpx +import hmac +import hashlib + +class WebhookChannel(NotificationChannel): + """Webhook notification channel for external systems.""" + + def __init__(self, secret: str = None): + self.secret = secret + + async def send(self, message: NotificationMessage) -> NotificationResult: + """Send webhook notification.""" + try: + # Build payload + payload = { + "event": message.template, + "recipient": message.recipient, + "timestamp": datetime.now(timezone.utc).isoformat(), + "data": message.variables or {} + } + + # Add signature if secret configured + headers = {"Content-Type": "application/json"} + if self.secret: + signature = hmac.new( + self.secret.encode(), + json.dumps(payload).encode(), + hashlib.sha256 + ).hexdigest() + headers["X-Webhook-Signature"] = signature + + async with httpx.AsyncClient() as client: + response = await client.post( + message.recipient, # Webhook URL + json=payload, + headers=headers, + timeout=10.0 + ) + response.raise_for_status() + + logger.info(f"Webhook sent to {message.recipient}") + return NotificationResult(success=True) + + except Exception as e: + logger.error(f"Failed to send webhook to {message.recipient}: {e}") + return NotificationResult( + success=False, + error=str(e) + ) + + def validate_recipient(self, recipient: str) -> bool: + """Validate webhook URL.""" + return recipient.startswith(("http://", "https://")) +``` + +**Notification service**: +```python +class NotificationService: + """Service for sending order-related notifications.""" + + def __init__(self, db): + self.db = db + self.channels: Dict[NotificationType, NotificationChannel] = {} + self.retry_queue = asyncio.Queue() + + def register_channel( + self, + channel_type: NotificationType, + channel: NotificationChannel + ): + """Register a notification channel.""" + self.channels[channel_type] = channel + logger.info(f"Registered notification channel: {channel_type.value}") + + async def send_order_notification( + self, + order_id: int, + event: NotificationEvent, + channels: List[NotificationType] = None + ): + """Send notification for order event.""" + if channels is None: + channels = [NotificationType.EMAIL] + + # Get order and customer details + async with self.db.acquire() as conn: + order = await conn.fetchrow( + """SELECT o.*, c.email, c.phone, c.first_name, c.last_name + FROM orders o + JOIN customers c ON c.id = o.customer_id + WHERE o.id = $1""", + order_id + ) + + if not order: + logger.warning(f"Order not found for notification: {order_id}") + return + + variables = { + "order_number": order["order_number"], + "customer_name": f"{order['first_name']} {order['last_name']}".strip(), + "total_amount": str(order["total_amount"]), + "currency": order["currency"], + "tracking_number": order.get("tracking_number", ""), + "carrier": order.get("shipping_carrier", ""), + "estimated_delivery": order.get("estimated_delivery_at", ""), + } + + # Add event-specific variables + if event == NotificationEvent.PAYMENT_RECEIVED: + variables["amount"] = str(order["total_amount"]) + elif event == NotificationEvent.ORDER_CANCELLED: + variables["reason"] = order.get("cancelled_reason", "Customer request") + elif event == NotificationEvent.REFUND_PROCESSED: + variables["amount"] = str(order.get("refunded_amount", "0")) + + # Send via each channel + for channel_type in channels: + channel = self.channels.get(channel_type) + if not channel: + logger.warning(f"Channel not configured: {channel_type.value}") + continue + + # Determine recipient + recipient = None + if channel_type == NotificationType.EMAIL: + recipient = order["email"] + elif channel_type == NotificationType.SMS: + recipient = order.get("phone") + + if not recipient or not channel.validate_recipient(recipient): + logger.warning(f"Invalid recipient for {channel_type.value}: {recipient}") + continue + + # Create message + message = NotificationMessage( + recipient=recipient, + type=channel_type, + template=event.value, + variables=variables + ) + + # Send + result = await channel.send(message) + + # Record in database + await self._record_notification( + order_id=order_id, + customer_id=order["customer_id"], + channel_type=channel_type.value, + template=event.value, + recipient=recipient, + status="sent" if result.success else "failed", + error_message=result.error + ) + + # Queue for retry if failed + if not result.success: + await self.retry_queue.put({ + "order_id": order_id, + "event": event, + "channel": channel_type, + "variables": variables, + "attempts": 1 + }) + + # Convenience methods for specific events + async def send_order_confirmation(self, order_id: int): + """Send order confirmation notification.""" + await self.send_order_notification( + order_id, + NotificationEvent.ORDER_CONFIRMED, + [NotificationType.EMAIL] + ) + + async def send_payment_confirmation(self, order_id: int): + """Send payment confirmation notification.""" + await self.send_order_notification( + order_id, + NotificationEvent.PAYMENT_RECEIVED, + [NotificationType.EMAIL] + ) + + async def send_shipping_notification(self, order_id: int): + """Send shipping notification.""" + await self.send_order_notification( + order_id, + NotificationEvent.ORDER_SHIPPED, + [NotificationType.EMAIL, NotificationType.SMS] + ) + + async def send_delivery_notification(self, order_id: int): + """Send delivery notification.""" + await self.send_order_notification( + order_id, + NotificationEvent.ORDER_DELIVERED, + [NotificationType.EMAIL] + ) + + async def send_cancellation_notification(self, order_id: int): + """Send cancellation notification.""" + await self.send_order_notification( + order_id, + NotificationEvent.ORDER_CANCELLED, + [NotificationType.EMAIL] + ) + + async def send_refund_notification(self, order_id: int): + """Send refund notification.""" + await self.send_order_notification( + order_id, + NotificationEvent.REFUND_PROCESSED, + [NotificationType.EMAIL] + ) + + async def _record_notification( + self, + order_id: int, + customer_id: int, + channel_type: str, + template: str, + recipient: str, + status: str, + error_message: str = None + ): + """Record notification in database.""" + async with self.db.acquire() as conn: + await conn.execute( + """INSERT INTO notifications + (customer_id, order_id, type, template, recipient, status, error_message) + VALUES ($1, $2, $3, $4, $5, $6, $7)""", + customer_id, order_id, channel_type, template, recipient, status, error_message + ) + + async def process_retry_queue(self): + """Background task to retry failed notifications.""" + while True: + try: + item = await self.retry_queue.get() + + if item["attempts"] >= 3: + logger.warning(f"Max retries exceeded for notification: {item}") + continue + + # Wait before retry (exponential backoff) + await asyncio.sleep(60 * (2 ** item["attempts"])) + + # Retry + channel = self.channels.get(item["channel"]) + if channel: + message = NotificationMessage( + recipient=item["variables"].get("recipient", ""), + type=item["channel"], + template=item["event"].value, + variables=item["variables"] + ) + + result = await channel.send(message) + + if result.success: + logger.info(f"Retry successful for notification to order {item['order_id']}") + else: + await self.retry_queue.put({ + **item, + "attempts": item["attempts"] + 1 + }) + + except Exception as e: + logger.error(f"Error in retry queue: {e}") + + await asyncio.sleep(1) +``` + +**Notification preferences**: +```sql +-- Customer notification preferences +CREATE TABLE notification_preferences ( + id BIGSERIAL PRIMARY KEY, + customer_id BIGINT NOT NULL REFERENCES customers(id) ON DELETE CASCADE, + channel VARCHAR(20) NOT NULL, + enabled BOOLEAN DEFAULT TRUE, + created_at TIMESTAMP NOT NULL DEFAULT NOW(), + updated_at TIMESTAMP NOT NULL DEFAULT NOW(), + UNIQUE(customer_id, channel) +); + +CREATE INDEX idx_notif_prefs_customer ON notification_preferences(customer_id); + +-- Default preferences +INSERT INTO notification_preferences (customer_id, channel, enabled) +SELECT id, 'email', TRUE FROM customers +ON CONFLICT DO NOTHING; +``` + +## Acceptance Criteria + +- [ ] Order confirmation emails are sent +- [ ] Shipping notifications include tracking +- [ ] SMS notifications work for shipping +- [ ] Failed notifications are retried +- [ ] Notifications are recorded in database +- [ ] Invalid recipients are handled gracefully +- [ ] Customer preferences are respected + +## Notes + +**Trade-offs**: +- Sync vs async sending: Async for responsiveness +- Built-in templates vs external service: Built-in for control + +**Performance**: +- Use message queue for high volume +- Batch email sending +- Implement rate limiting for SMS + +**Alternatives considered**: +- SendGrid/Mailgun: Simplifies email but adds dependency +- Push notifications: Mobile app required diff --git a/ai_coder_1/subtasks/Decomp-004-09.md b/ai_coder_1/subtasks/Decomp-004-09.md new file mode 100644 index 0000000..d32a9a5 --- /dev/null +++ b/ai_coder_1/subtasks/Decomp-004-09.md @@ -0,0 +1,654 @@ +# Subtask: Order Analytics and Reporting + +**Parent Task**: Decomp/004 +**Subtask ID**: Decomp-004-09 +**Dependencies**: Decomp-004-01 (Database Schema) + +## Description + +Implement order analytics and reporting system. Provide sales metrics, revenue tracking, customer analytics, and product performance data. Support real-time dashboards and scheduled reports. + +## Requirements + +- Sales revenue tracking (daily, weekly, monthly) +- Order volume metrics +- Product performance analytics +- Customer lifetime value calculation +- Conversion rate tracking +- Average order value +- Revenue by category/product +- Export functionality (CSV, PDF) + +## Technical Specifications + +**Analytics service**: +```python +from datetime import datetime, timedelta, timezone +from typing import List, Dict, Any, Optional +from dataclasses import dataclass, field +from decimal import Decimal +import logging + +logger = logging.getLogger(__name__) + +@dataclass +class SalesMetrics: + """Sales metrics for a period.""" + period_start: datetime + period_end: datetime + total_orders: int + completed_orders: int + cancelled_orders: int + total_revenue: Decimal + refunded_amount: Decimal + net_revenue: Decimal + average_order_value: Decimal + conversion_rate: float # Percentage + unique_customers: int + +@dataclass +class ProductSales: + """Product sales data.""" + product_id: int + sku: str + name: str + category: str + units_sold: int + revenue: Decimal + profit: Decimal + refund_rate: float + +@dataclass +class CustomerAnalytics: + """Customer analytics data.""" + customer_id: int + total_orders: int + total_spent: Decimal + average_order_value: Decimal + first_order_date: datetime + last_order_date: datetime + lifetime_value: Decimal + +@dataclass +class CategorySales: + """Category sales data.""" + category_id: int + category_name: str + total_orders: int + total_revenue: Decimal + top_products: List[Dict] = field(default_factory=list) + +class OrderAnalyticsService: + """Service for order analytics and reporting.""" + + def __init__(self, db): + self.db = db + + async def get_sales_metrics( + self, + start_date: datetime = None, + end_date: datetime = None + ) -> SalesMetrics: + """Get sales metrics for a date range.""" + if not end_date: + end_date = datetime.now(timezone.utc) + if not start_date: + start_date = end_date - timedelta(days=30) + + async with self.db.acquire() as conn: + # Order counts + counts = await conn.fetchrow( + """SELECT + COUNT(*) FILTER (WHERE created_at >= $1 AND created_at <= $2) as total_orders, + COUNT(*) FILTER (WHERE status IN ('paid', 'shipped', 'delivered') + AND created_at >= $1 AND created_at <= $2) as completed_orders, + COUNT(*) FILTER (WHERE status = 'cancelled' + AND created_at >= $1 AND created_at <= $2) as cancelled_orders + FROM orders""", + start_date, end_date + ) + + # Revenue metrics + revenue = await conn.fetchrow( + """SELECT + COALESCE(SUM(total_amount), 0) as total_revenue, + COALESCE(SUM(refunded_amount), 0) as refunded_amount + FROM orders + WHERE created_at >= $1 AND created_at <= $2 + AND status NOT IN ('pending', 'cancelled')""", + start_date, end_date + ) + + # Average order value + aov = await conn.fetchval( + """SELECT COALESCE(AVG(total_amount), 0) + FROM orders + WHERE created_at >= $1 AND created_at <= $2 + AND status NOT IN ('pending', 'cancelled')""", + start_date, end_date + ) + + # Unique customers + unique_customers = await conn.fetchval( + """SELECT COUNT(DISTINCT customer_id) + FROM orders + WHERE created_at >= $1 AND created_at <= $2""", + start_date, end_date + ) + + # Conversion rate (orders / unique visitors - mock) + # In production, integrate with web analytics + conversion_rate = 2.5 # Mock value + + total_revenue = Decimal(str(revenue["total_revenue"])) + refunded_amount = Decimal(str(revenue["refunded_amount"])) + + return SalesMetrics( + period_start=start_date, + period_end=end_date, + total_orders=counts["total_orders"] or 0, + completed_orders=counts["completed_orders"] or 0, + cancelled_orders=counts["cancelled_orders"] or 0, + total_revenue=total_revenue, + refunded_amount=refunded_amount, + net_revenue=total_revenue - refunded_amount, + average_order_value=Decimal(str(aov)) if aov else Decimal("0"), + conversion_rate=conversion_rate, + unique_customers=unique_customers or 0 + ) + + async def get_daily_sales( + self, + days: int = 30 + ) -> List[Dict[str, Any]]: + """Get daily sales breakdown.""" + start_date = datetime.now(timezone.utc) - timedelta(days=days) + + async with self.db.acquire() as conn: + rows = await conn.fetch( + """SELECT + DATE(created_at) as date, + COUNT(*) as orders, + COUNT(*) FILTER (WHERE status NOT IN ('pending', 'cancelled')) as completed, + COALESCE(SUM(total_amount) FILTER (WHERE status NOT IN ('pending', 'cancelled')), 0) as revenue, + COALESCE(SUM(refunded_amount), 0) as refunded + FROM orders + WHERE created_at >= $1 + GROUP BY DATE(created_at) + ORDER BY date DESC""", + start_date + ) + + return [ + { + "date": row["date"].isoformat(), + "orders": row["orders"], + "completed": row["completed"], + "revenue": str(row["revenue"]), + "refunded": str(row["refunded"]), + "net_revenue": str(row["revenue"] - row["refunded"]) + } + for row in rows + ] + + async def get_product_sales( + self, + start_date: datetime = None, + end_date: datetime = None, + limit: int = 50 + ) -> List[ProductSales]: + """Get top-selling products.""" + if not end_date: + end_date = datetime.now(timezone.utc) + if not start_date: + start_date = end_date - timedelta(days=30) + + async with self.db.acquire() as conn: + rows = await conn.fetch( + """SELECT + p.id as product_id, + p.sku, + p.name, + c.name as category, + COALESCE(SUM(oi.quantity), 0) as units_sold, + COALESCE(SUM(oi.total_amount), 0) as revenue + FROM order_items oi + JOIN orders o ON o.id = oi.order_id + JOIN products p ON p.id = oi.product_id + LEFT JOIN categories c ON c.id = p.category_id + WHERE o.created_at >= $1 AND o.created_at <= $2 + AND o.status NOT IN ('pending', 'cancelled') + GROUP BY p.id, p.sku, p.name, c.name + ORDER BY revenue DESC + LIMIT $3""", + start_date, end_date, limit + ) + + # Calculate profit and refund rate for each product + result = [] + for row in rows: + # Get refund info + refunds = await conn.fetchrow( + """SELECT COALESCE(SUM(r.amount), 0) as refund_total + FROM refunds r + JOIN payment_transactions pt ON pt.id = r.payment_transaction_id + JOIN order_items oi ON oi.order_id = pt.order_id + WHERE oi.product_id = $1""", + row["product_id"] + ) + + refund_amount = Decimal(str(refunds["refund_total"])) if refunds else Decimal("0") + revenue = Decimal(str(row["revenue"])) + profit = revenue * Decimal("0.3") # Assume 30% margin + + result.append(ProductSales( + product_id=row["product_id"], + sku=row["sku"], + name=row["name"], + category=row.get("category", "Uncategorized"), + units_sold=row["units_sold"], + revenue=revenue, + profit=profit - refund_amount, + refund_rate=float(refund_amount / revenue * 100) if revenue > 0 else 0 + )) + + return result + + async def get_category_sales( + self, + start_date: datetime = None, + end_date: datetime = None + ) -> List[CategorySales]: + """Get sales by category.""" + if not end_date: + end_date = datetime.now(timezone.utc) + if not start_date: + start_date = end_date - timedelta(days=30) + + async with self.db.acquire() as conn: + rows = await conn.fetch( + """SELECT + c.id as category_id, + COALESCE(c.name, 'Uncategorized') as category_name, + COUNT(DISTINCT o.id) as total_orders, + COALESCE(SUM(oi.total_amount), 0) as total_revenue + FROM order_items oi + JOIN orders o ON o.id = oi.order_id + JOIN products p ON p.id = oi.product_id + LEFT JOIN categories c ON c.id = p.category_id + WHERE o.created_at >= $1 AND o.created_at <= $2 + AND o.status NOT IN ('pending', 'cancelled') + GROUP BY c.id, c.name + ORDER BY total_revenue DESC""", + start_date, end_date + ) + + result = [] + for row in rows: + # Get top products in category + top_products = await conn.fetch( + """SELECT p.name, SUM(oi.quantity) as units, SUM(oi.total_amount) as revenue + FROM order_items oi + JOIN orders o ON o.id = oi.order_id + JOIN products p ON p.id = oi.product_id + WHERE p.category_id = $1 + AND o.created_at >= $2 AND o.created_at <= $3 + AND o.status NOT IN ('pending', 'cancelled') + GROUP BY p.id, p.name + ORDER BY revenue DESC + LIMIT 5""", + row["category_id"], start_date, end_date + ) + + result.append(CategorySales( + category_id=row["category_id"], + category_name=row["category_name"], + total_orders=row["total_orders"], + total_revenue=Decimal(str(row["total_revenue"])), + top_products=[dict(p) for p in top_products] + )) + + return result + + async def get_customer_analytics( + self, + customer_id: int + ) -> CustomerAnalytics: + """Get analytics for a specific customer.""" + async with self.db.acquire() as conn: + row = await conn.fetchrow( + """SELECT + customer_id, + COUNT(*) as total_orders, + COALESCE(SUM(total_amount), 0) as total_spent, + COALESCE(AVG(total_amount), 0) as average_order_value, + MIN(created_at) as first_order_date, + MAX(created_at) as last_order_date + FROM orders + WHERE customer_id = $1 + AND status NOT IN ('pending', 'cancelled') + GROUP BY customer_id""", + customer_id + ) + + if not row: + return None + + # Calculate lifetime value (CLV) + # Simple formula: AOV * purchase_frequency * customer_lifespan + # Using 3 years as average lifespan + total_spent = Decimal(str(row["total_spent"])) + total_orders = row["total_orders"] + aov = Decimal(str(row["average_order_value"])) + + # Estimate annual orders + if row["first_order_date"]: + days_active = (datetime.now(timezone.utc) - row["first_order_date"]).days + orders_per_year = (total_orders / max(days_active, 1)) * 365 if days_active > 0 else 0 + else: + orders_per_year = 0 + + lifetime_value = aov * orders_per_year * 3 # 3 years + + return CustomerAnalytics( + customer_id=customer_id, + total_orders=total_orders, + total_spent=total_spent, + average_order_value=aov, + first_order_date=row["first_order_date"], + last_order_date=row["last_order_date"], + lifetime_value=lifetime_value + ) + + async def get_top_customers( + self, + start_date: datetime = None, + end_date: datetime = None, + limit: int = 50 + ) -> List[Dict[str, Any]]: + """Get top customers by revenue.""" + if not end_date: + end_date = datetime.now(timezone.utc) + if not start_date: + start_date = end_date - timedelta(days=90) + + async with self.db.acquire() as conn: + rows = await conn.fetch( + """SELECT + o.customer_id, + c.email, + c.first_name, + c.last_name, + COUNT(*) as orders, + COALESCE(SUM(o.total_amount), 0) as total_spent, + COALESCE(AVG(o.total_amount), 0) as avg_order + FROM orders o + JOIN customers c ON c.id = o.customer_id + WHERE o.created_at >= $1 AND o.created_at <= $2 + AND o.status NOT IN ('pending', 'cancelled') + GROUP BY o.customer_id, c.email, c.first_name, c.last_name + ORDER BY total_spent DESC + LIMIT $3""", + start_date, end_date, limit + ) + + return [ + { + "customer_id": row["customer_id"], + "email": row["email"], + "name": f"{row['first_name']} {row['last_name']}".strip(), + "orders": row["orders"], + "total_spent": str(row["total_spent"]), + "average_order": str(row["avg_order"]) + } + for row in rows + ] + + async def get_revenue_summary( + self, + group_by: str = "day" # day, week, month + ) -> List[Dict[str, Any]]: + """Get revenue summary grouped by time period.""" + async with self.db.acquire() as conn: + if group_by == "day": + date_trunc = "DATE(created_at)" + interval = "1 day" + elif group_by == "week": + date_trunc = "date_trunc('week', created_at)" + interval = "1 week" + else: # month + date_trunc = "date_trunc('month', created_at)" + interval = "1 month" + + rows = await conn.fetch( + f"""SELECT + {date_trunc} as period, + COUNT(*) FILTER (WHERE status NOT IN ('pending', 'cancelled')) as orders, + COALESCE(SUM(total_amount) FILTER (WHERE status NOT IN ('pending', 'cancelled')), 0) as revenue, + COALESCE(SUM(refunded_amount), 0) as refunds + FROM orders + WHERE created_at >= NOW() - INTERVAL '1 year' + GROUP BY {date_trunc} + ORDER BY period DESC + LIMIT 52""" + ) + + return [ + { + "period": row["period"].isoformat() hasattr(row["period"], "isoformat") else str(row["period"]), + "orders": row["orders"], + "revenue": str(row["revenue"]), + "refunds": str(row["refunds"]), + "net_revenue": str(row["revenue"] - row["refunds"]) + } + for row in rows + ] + + async def export_report( + self, + report_type: str, + start_date: datetime, + end_date: datetime, + format: str = "csv" + ) -> bytes: + """Export a report in specified format.""" + if report_type == "sales": + data = await self.get_daily_sales( + days=(end_date - start_date).days + ) + elif report_type == "products": + data = await self.get_product_sales(start_date, end_date) + elif report_type == "customers": + data = await self.get_top_customers(start_date, end_date) + else: + raise ValueError(f"Unknown report type: {report_type}") + + if format == "csv": + return self._export_csv(data) + elif format == "json": + return self._export_json(data) + else: + raise ValueError(f"Unknown format: {format}") + + def _export_csv(self, data: List[Dict]) -> bytes: + """Export data as CSV.""" + import csv + import io + + output = io.StringIO() + if not data: + return output.getvalue().encode('utf-8') + + writer = csv.DictWriter(output, fieldnames=data[0].keys()) + writer.writeheader() + writer.writerows(data) + + return output.getvalue().encode('utf-8') + + def _export_json(self, data: List[Dict]) -> bytes: + """Export data as JSON.""" + import json + return json.dumps(data, default=str).encode('utf-8') +``` + +**Dashboard API**: +```python +from fastapi import APIRouter, Query +from typing import Optional +from datetime import datetime, timedelta + +router = APIRouter(prefix="/analytics", tags=["analytics"]) + +@router.get("/sales/summary") +async def sales_summary( + days: int = Query(30, description="Number of days"), + start_date: Optional[datetime] = None, + end_date: Optional[datetime] = None +): + """Get sales summary metrics.""" + analytics = get_analytics_service() + + if start_date and end_date: + metrics = await analytics.get_sales_metrics(start_date, end_date) + else: + metrics = await analytics.get_sales_metrics() + + return { + "period": { + "start": metrics.period_start.isoformat(), + "end": metrics.period_end.isoformat() + }, + "orders": { + "total": metrics.total_orders, + "completed": metrics.completed_orders, + "cancelled": metrics.cancelled_orders + }, + "revenue": { + "gross": str(metrics.total_revenue), + "refunded": str(metrics.refunded_amount), + "net": str(metrics.net_revenue), + "average_order": str(metrics.average_order_value) + }, + "customers": { + "unique": metrics.unique_customers, + "conversion_rate": metrics.conversion_rate + } + } + +@router.get("/sales/daily") +async def daily_sales(days: int = Query(30, ge=1, le=365)): + """Get daily sales breakdown.""" + analytics = get_analytics_service() + data = await analytics.get_daily_sales(days) + return {"data": data} + +@router.get("/products/top") +async def top_products( + start_date: Optional[datetime] = None, + end_date: Optional[datetime] = None, + limit: int = Query(50, ge=1, le=100) +): + """Get top-selling products.""" + analytics = get_analytics_service() + data = await analytics.get_product_sales(start_date, end_date, limit) + return { + "products": [ + { + "product_id": p.product_id, + "sku": p.sku, + "name": p.name, + "category": p.category, + "units_sold": p.units_sold, + "revenue": str(p.revenue), + "profit": str(p.profit), + "refund_rate": round(p.refund_rate, 2) + } + for p in data + ] + } + +@router.get("/customers/top") +async def top_customers( + start_date: Optional[datetime] = None, + end_date: Optional[datetime] = None, + limit: int = Query(50, ge=1, le=100) +): + """Get top customers by revenue.""" + analytics = get_analytics_service() + data = await analytics.get_top_customers(start_date, end_date, limit) + return {"customers": data} + +@router.get("/categories") +async def category_sales( + start_date: Optional[datetime] = None, + end_date: Optional[datetime] = None +): + """Get sales by category.""" + analytics = get_analytics_service() + data = await analytics.get_category_sales(start_date, end_date) + return { + "categories": [ + { + "category_id": c.category_id, + "name": c.category_name, + "orders": c.total_orders, + "revenue": str(c.total_revenue), + "top_products": c.top_products + } + for c in data + ] + } + +@router.get("/export/{report_type}") +async def export_report( + report_type: str, + start_date: datetime, + end_date: datetime, + format: str = Query("csv", regex="^(csv|json)$") +): + """Export a report.""" + analytics = get_analytics_service() + + data = await analytics.export_report( + report_type=report_type, + start_date=start_date, + end_date=end_date, + format=format + ) + + from fastapi.responses import Response + media_type = "text/csv" if format == "csv" else "application/json" + + return Response( + content=data, + media_type=media_type, + headers={ + "Content-Disposition": f"attachment; filename={report_type}_{start_date.date()}_to_{end_date.date()}.{format}" + } + ) +``` + +## Acceptance Criteria + +- [ ] Sales metrics are calculated correctly +- [ ] Daily sales breakdown works +- [ ] Top products list is accurate +- [ ] Customer analytics are computed +- [ ] Category sales are aggregated +- [ ] Reports can be exported as CSV/JSON +- [ ] Date range filtering works + +## Notes + +**Trade-offs**: +- Real-time vs batch aggregation: Batch for efficiency +- Built-in vs external BI: Built-in for simplicity + +**Performance**: +- Materialized views for common queries +- Pre-aggregate data with scheduled jobs +- Cache results for dashboard + +**Alternatives considered**: +- Tableau/Metabase integration: Better for complex dashboards +- ClickHouse for analytics: Overkill for current scale diff --git a/ai_coder_1/subtasks/Decomp-005-01.md b/ai_coder_1/subtasks/Decomp-005-01.md new file mode 100644 index 0000000..3258a3e --- /dev/null +++ b/ai_coder_1/subtasks/Decomp-005-01.md @@ -0,0 +1,445 @@ +# Subtask: Storage Architecture and Metadata + +**Parent Task**: Decomp/005 +**Subtask ID**: Decomp/005-01 +**Dependencies**: None + +## Description + +Design storage architecture for distributed object storage system. Define metadata schema, bucket organization, data distribution strategy, and consistency guarantees. + +## Requirements + +- Bucket-based file organization +- Metadata storage for files +- Data partitioning across nodes +- Consistent hashing for distribution +- Checksum-based integrity verification +- Support for large files (multi-part) +- Version tracking +- Access control metadata + +## Technical Specifications + +**Storage architecture overview**: +``` +┌─────────────────────────────────────────────────────────────┐ +│ API Layer │ +├─────────────────────────────────────────────────────────────┤ +│ Metadata Service │ +│ - PostgreSQL for metadata │ +│ - Redis for hot metadata cache │ +├─────────────────────────────────────────────────────────────┤ +│ Storage Engine │ +│ - Consistent Hash Ring │ +│ - Replication Manager │ +│ - Local Storage Adapter │ +├─────────────────────────────────────────────────────────────┤ +│ Storage Nodes (N replicas) │ +│ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ │ +│ │ Node 1 │ │ Node 2 │ │ Node 3 │ │ Node 4 │ │ +│ └─────────┘ └─────────┘ └─────────┘ └─────────┘ │ +└─────────────────────────────────────────────────────────────┘ +``` + +**Metadata schema (PostgreSQL)**: +```sql +-- Buckets (containers for files) +CREATE TABLE buckets ( + id BIGSERIAL PRIMARY KEY, + name VARCHAR(255) NOT NULL UNIQUE, + owner_id BIGINT NOT NULL, + region VARCHAR(50) DEFAULT 'us-east-1', + storage_class VARCHAR(20) DEFAULT 'standard', -- standard, infrequent, archive + versioning_enabled BOOLEAN DEFAULT FALSE, + quota_bytes BIGINT, + used_bytes BIGINT DEFAULT 0, + object_count INTEGER DEFAULT 0, + created_at TIMESTAMP NOT NULL DEFAULT NOW(), + updated_at TIMESTAMP NOT NULL DEFAULT NOW(), + metadata JSONB DEFAULT '{}'::jsonb +); + +CREATE INDEX idx_buckets_owner ON buckets(owner_id); +CREATE INDEX idx_buckets_name ON buckets(name); + +-- Objects (files) +CREATE TABLE objects ( + id BIGSERIAL PRIMARY KEY, + bucket_id BIGINT NOT NULL REFERENCES buckets(id) ON DELETE CASCADE, + object_key VARCHAR(1024) NOT NULL, -- Full path including "folders" + version_id VARCHAR(100) UNIQUE, -- NULL if versioning disabled + is_latest BOOLEAN DEFAULT TRUE, + is_delete_marker BOOLEAN DEFAULT FALSE, + + -- File metadata + content_type VARCHAR(255), + content_encoding VARCHAR(50), + content_language VARCHAR(50), + content_length BIGINT NOT NULL, + etag VARCHAR(100) NOT NULL, -- MD5 hash + checksum_sha256 VARCHAR(100), + + -- Storage metadata + storage_class VARCHAR(20) DEFAULT 'standard', + storage_nodes JSONB, -- List of node IDs holding this object + + -- Timestamps + created_at TIMESTAMP NOT NULL DEFAULT NOW(), + modified_at TIMESTAMP NOT NULL DEFAULT NOW(), + accessed_at TIMESTAMP, + + -- Additional metadata + user_metadata JSONB DEFAULT '{}'::jsonb, + custom_tags JSONB DEFAULT '{}'::jsonb, + + UNIQUE(bucket_id, object_key, version_id) +); + +CREATE INDEX idx_objects_bucket ON objects(bucket_id); +CREATE INDEX idx_objects_key ON objects(bucket_id, object_key); +CREATE INDEX idx_objects_version ON objects(bucket_id, object_key, version_id); +CREATE INDEX idx_objects_latest ON objects(bucket_id, object_key) WHERE is_latest = TRUE; + +-- Multipart uploads +CREATE TABLE multipart_uploads ( + id BIGSERIAL PRIMARY KEY, + upload_id VARCHAR(100) NOT NULL UNIQUE, + bucket_id BIGINT NOT NULL REFERENCES buckets(id), + object_key VARCHAR(1024) NOT NULL, + content_type VARCHAR(255), + owner_id BIGINT NOT NULL, + initiated_at TIMESTAMP NOT NULL DEFAULT NOW(), + expires_at TIMESTAMP NOT NULL, + parts_uploaded INTEGER DEFAULT 0, + total_parts INTEGER, + metadata JSONB DEFAULT '{}'::jsonb +); + +CREATE INDEX idx_multipart_uploads_id ON multipart_uploads(upload_id); +CREATE INDEX idx_multipart_uploads_expires ON multipart_uploads(expires_at) + WHERE expires_at > NOW(); + +-- Multipart upload parts +CREATE TABLE multipart_parts ( + id BIGSERIAL PRIMARY KEY, + upload_id VARCHAR(100) NOT NULL REFERENCES multipart_uploads(upload_id) ON DELETE CASCADE, + part_number INTEGER NOT NULL, + object_id BIGINT NOT NULL REFERENCES objects(id), + size_bytes BIGINT NOT NULL, + etag VARCHAR(100) NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT NOW(), + UNIQUE(upload_id, part_number) +); + +CREATE INDEX idx_multipart_parts_upload ON multipart_parts(upload_id, part_number); + +-- Access Control Lists +CREATE TABLE acls ( + id BIGSERIAL PRIMARY KEY, + resource_type VARCHAR(20) NOT NULL, -- 'bucket' or 'object' + resource_id BIGINT NOT NULL, + grantee_type VARCHAR(20) NOT NULL, -- 'user', 'group', 'all' + grantee_id VARCHAR(255), -- User ID, group name, or NULL for 'all' + permission VARCHAR(20) NOT NULL, -- 'read', 'write', 'read_acl', 'write_acl', 'full_control' + created_at TIMESTAMP NOT NULL DEFAULT NOW() +); + +CREATE INDEX idx_acls_resource ON acls(resource_type, resource_id); + +-- Presigned URLs +CREATE TABLE presigned_urls ( + id BIGSERIAL PRIMARY KEY, + object_id BIGINT NOT NULL REFERENCES objects(id) ON DELETE CASCADE, + access_key VARCHAR(100) NOT NULL UNIQUE, + expires_at TIMESTAMP NOT NULL, + operation VARCHAR(10) NOT NULL, -- 'get', 'put', 'delete' + created_at TIMESTAMP NOT NULL DEFAULT NOW() +); + +CREATE INDEX idx_presigned_key ON presigned_urls(access_key); +CREATE INDEX idx_presigned_expires ON presigned_urls(expires_at) WHERE expires_at > NOW(); + +-- Storage nodes registration +CREATE TABLE storage_nodes ( + id SERIAL PRIMARY KEY, + node_id VARCHAR(100) NOT NULL UNIQUE, + hostname VARCHAR(255) NOT NULL, + port INTEGER DEFAULT 8080, + storage_path VARCHAR(500) NOT NULL, + capacity_bytes BIGINT NOT NULL, + used_bytes BIGINT DEFAULT 0, + status VARCHAR(20) DEFAULT 'active', -- active, draining, maintenance, offline + region VARCHAR(50), + zone VARCHAR(50), + weight INTEGER DEFAULT 100, -- For weighted consistent hashing + last_heartbeat TIMESTAMP NOT NULL DEFAULT NOW(), + metadata JSONB DEFAULT '{}'::jsonb, + created_at TIMESTAMP NOT NULL DEFAULT NOW() +); + +CREATE INDEX idx_nodes_status ON storage_nodes(status); +CREATE INDEX idx_nodes_heartbeat ON storage_nodes(last_heartbeat); + +-- Replication status +CREATE TABLE replication_status ( + id BIGSERIAL PRIMARY KEY, + object_id BIGINT NOT NULL REFERENCES objects(id) ON DELETE CASCADE, + source_node VARCHAR(100), + target_node VARCHAR(100), + status VARCHAR(20) NOT NULL, -- pending, in_progress, completed, failed + started_at TIMESTAMP, + completed_at TIMESTAMP, + error_message TEXT +); + +CREATE INDEX idx_replication_object ON replication_status(object_id); +CREATE INDEX idx_replication_status ON replication_status(status); + +-- Lifecycle policies +CREATE TABLE lifecycle_policies ( + id BIGSERIAL PRIMARY KEY, + bucket_id BIGINT NOT NULL REFERENCES buckets(id) ON DELETE CASCADE, + name VARCHAR(255) NOT NULL, + rules JSONB NOT NULL, -- Transition/expiration rules + is_enabled BOOLEAN DEFAULT TRUE, + created_at TIMESTAMP NOT NULL DEFAULT NOW(), + updated_at TIMESTAMP NOT NULL DEFAULT NOW() +); + +CREATE INDEX idx_lifecycle_bucket ON lifecycle_policies(bucket_id); + +-- Audit log +CREATE TABLE audit_log ( + id BIGSERIAL PRIMARY KEY, + bucket_id BIGINT REFERENCES buckets(id), + object_id BIGINT REFERENCES objects(id), + operation VARCHAR(20) NOT NULL, -- GET, PUT, DELETE, HEAD, LIST + user_id VARCHAR(255), + access_key_id VARCHAR(100), + request_id VARCHAR(100), + source_ip VARCHAR(50), + user_agent TEXT, + http_status INTEGER, + error_code VARCHAR(50), + bytes_sent BIGINT, + bytes_received BIGINT, + operation_time TIMESTAMP NOT NULL DEFAULT NOW(), + details JSONB DEFAULT '{}'::jsonb +); + +CREATE INDEX idx_audit_log_time ON audit_log(operation_time DESC); +CREATE INDEX idx_audit_log_bucket ON audit_log(bucket_id, operation_time DESC); +CREATE INDEX idx_audit_log_object ON audit_log(object_id, operation_time DESC); + +-- Functions and triggers +CREATE OR REPLACE FUNCTION update_bucket_stats() +RETURNS TRIGGER AS $$ +BEGIN + IF TG_OP = 'INSERT' THEN + UPDATE buckets + SET used_bytes = used_bytes + NEW.content_length, + object_count = object_count + 1, + updated_at = NOW() + WHERE id = NEW.bucket_id; + ELSIF TG_OP = 'DELETE' THEN + UPDATE buckets + SET used_bytes = used_bytes - OLD.content_length, + object_count = object_count - 1, + updated_at = NOW() + WHERE id = OLD.bucket_id; + END IF; + RETURN NULL; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER update_bucket_stats_trigger + AFTER INSERT OR DELETE ON objects + FOR EACH ROW + EXECUTE FUNCTION update_bucket_stats(); + +-- Function to generate version ID +CREATE OR REPLACE FUNCTION generate_version_id() +RETURNS TRIGGER AS $$ +BEGIN + NEW.version_id := 'v-' || encode(gen_random_bytes(16), 'hex'); + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +-- Trigger for version ID (only when versioning enabled) +CREATE OR REPLACE FUNCTION check_versioning() +RETURNS TRIGGER AS $$ +DECLARE + versioning_enabled BOOLEAN; +BEGIN + SELECT b.versioning_enabled INTO versioning_enabled + FROM buckets b WHERE b.id = NEW.bucket_id; + + IF versioning_enabled THEN + PERFORM generate_version_id(); + NEW.version_id := 'v-' || encode(gen_random_bytes(16), 'hex'); + + -- Mark previous versions as not latest + UPDATE objects + SET is_latest = FALSE + WHERE bucket_id = NEW.bucket_id + AND object_key = NEW.object_key + AND is_latest = TRUE; + ELSE + -- Delete previous object if exists + DELETE FROM objects + WHERE bucket_id = NEW.bucket_id + AND object_key = NEW.object_key + AND is_latest = TRUE; + NEW.version_id := 'v-' || encode(gen_random_bytes(16), 'hex'); + END IF; + + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +-- Storage allocation view +CREATE VIEW storage_usage AS +SELECT + sn.id, + sn.node_id, + sn.hostname, + sn.capacity_bytes, + sn.used_bytes, + sn.capacity_bytes - sn.used_bytes as available_bytes, + ROUND((sn.used_bytes::NUMERIC / sn.capacity_bytes) * 100, 2) as usage_percent, + sn.status, + COUNT(DISTINCT o.id) as object_count +FROM storage_nodes sn +LEFT JOIN objects o ON o.storage_nodes @> to_jsonb(sn.node_id) +GROUP BY sn.id, sn.node_id, sn.hostname, sn.capacity_bytes, sn.used_bytes, sn.status; +``` + +**Consistent hashing configuration**: +```python +from dataclasses import dataclass +from typing import List, Dict, Optional +import hashlib +import bisect + +@dataclass +class HashRingConfig: + """Configuration for consistent hash ring.""" + virtual_nodes: int = 150 # Virtual nodes per physical node + replication_factor: int = 3 # Number of replicas + hash_function: str = "md5" # md5, sha1, sha256 + +class HashRing: + """Consistent hash ring for data distribution.""" + + def __init__(self, config: HashRingConfig): + self.config = config + self.ring: Dict[int, str] = {} # hash -> node_id + self.sorted_keys: List[int] = [] + self.nodes: Dict[str, dict] = {} + + def add_node(self, node_id: str, weight: int = 100): + """Add a node to the ring.""" + self.nodes[node_id] = {"weight": weight, "status": "active"} + + # Add virtual nodes based on weight + virtual_count = self.config.virtual_nodes * weight // 100 + + for i in range(virtual_count): + key = self._hash(f"{node_id}:{i}") + self.ring[key] = node_id + bisect.insort(self.sorted_keys, key) + + def remove_node(self, node_id: str): + """Remove a node from the ring.""" + self.nodes.pop(node_id, None) + + # Remove all virtual nodes + keys_to_remove = [k for k, v in self.ring.items() if v == node_id] + for key in keys_to_remove: + self.ring.pop(key) + self.sorted_keys.remove(key) + + def get_nodes(self, key: str) -> List[str]: + """Get replication nodes for a key.""" + if not self.sorted_keys: + return [] + + key_hash = self._hash(key) + idx = bisect.bisect_right(self.sorted_keys, key_hash) + nodes = [] + + # Get next N nodes + for _ in range(self.config.replication_factor * 10): # Limit iterations + if idx >= len(self.sorted_keys): + idx = 0 + + node_id = self.ring[self.sorted_keys[idx]] + if node_id not in nodes and self.nodes.get(node_id, {}).get("status") == "active": + nodes.append(node_id) + if len(nodes) >= self.config.replication_factor: + break + + idx += 1 + + return nodes + + def _hash(self, key: str) -> int: + """Hash a key to an integer.""" + if self.config.hash_function == "md5": + return int(hashlib.md5(key.encode()).hexdigest(), 16) + elif self.config.hash_function == "sha1": + return int(hashlib.sha1(key.encode()).hexdigest(), 16) + elif self.config.hash_function == "sha256": + return int(hashlib.sha256(key.encode()).hexdigest(), 16) + else: + return int(hashlib.md5(key.encode()).hexdigest(), 16) +``` + +**Storage node configuration**: +```python +@dataclass +class StorageNodeConfig: + """Configuration for a storage node.""" + node_id: str + hostname: str + port: int = 8080 + storage_path: str = "/data/storage" + capacity_bytes: int = 1_000_000_000_000 # 1TB default + region: str = "us-east-1" + zone: str = "a" + +@dataclass +class StorageClass: + """Storage class definitions.""" + name: str # standard, infrequent, archive + durability: int # 9s (e.g., 11 for 99.999999999%) + availability: str # 99.99% + min_storage_size: int = 0 + retrieval_time: str = "instant" # instant, minutes, hours + transition_days: int = None # Auto-transition after N days +``` + +## Acceptance Criteria + +- [ ] All tables created without errors +- [ ] Foreign key constraints enforced +- [ ] Hash ring distributes keys evenly +- [ ] Replication factor is respected +- [ ] Bucket stats update on object changes +- [ ] Version ID generation works + +## Notes + +**Trade-offs**: +- PostgreSQL vs NoSQL for metadata: PostgreSQL for ACID +- Consistent hashing vs simple modulo: Consistent hashing for rebalancing + +**Scalability**: +- Partition metadata by bucket_id for very large deployments +- Use read replicas for metadata queries + +**Alternatives considered**: +- DynamoDB for metadata: More expensive, eventual consistency +- Ceph for storage: More complex, overkill for this use case diff --git a/ai_coder_1/subtasks/Decomp-005-02.md b/ai_coder_1/subtasks/Decomp-005-02.md new file mode 100644 index 0000000..01ca8c1 --- /dev/null +++ b/ai_coder_1/subtasks/Decomp-005-02.md @@ -0,0 +1,648 @@ +# Subtask: File Upload API + +**Parent Task**: Decomp/005 +**Subtask ID**: Decomp-005-02 +**Dependencies**: Decomp-005-01 (Storage Architecture and Metadata) + +## Description + +Implement file upload API supporting single file uploads, metadata handling, checksum verification, and automatic replication. Support multiple upload methods (direct, presigned URL). + +## Requirements + +- Upload files to buckets +- Support files up to 5GB (single part) +- Calculate and verify MD5 checksums +- Handle content-type and custom metadata +- Automatic replication to storage nodes +- Progress tracking for uploads +- Presigned URL support for direct uploads +- Quota enforcement + +## Technical Specifications + +**Upload service**: +```python +from typing import Optional, Dict, Any, BinaryIO +from dataclasses import dataclass +from datetime import datetime, timezone, timedelta +from decimal import Decimal +from pathlib import Path +import hashlib +import uuid +import logging +import asyncio + +logger = logging.getLogger(__name__) + +@dataclass +class UploadResult: + """Result of file upload.""" + success: bool + object_id: int = None + version_id: str = None + etag: str = None + location: str = None + error: str = None + +@dataclass +class UploadProgress: + """Upload progress tracking.""" + bytes_uploaded: int + total_bytes: int + percentage: float + current_part: int = None + +class FileUploadService: + """Service for handling file uploads.""" + + def __init__( + self, + db, + hash_ring, + replication_service, + storage_adapter + ): + self.db = db + self.hash_ring = hash_ring + self.replication = replication_service + self.storage = storage_adapter + + async def upload_file( + self, + bucket_id: int, + object_key: str, + data: BinaryIO, + content_length: int, + content_type: str = None, + metadata: Dict[str, Any] = None, + storage_class: str = "standard" + ) -> UploadResult: + """ + Upload a file to a bucket. + + Args: + bucket_id: Target bucket ID + object_key: Object key (path/filename) + data: File data as readable stream + content_length: Size of file in bytes + content_type: MIME type + metadata: Custom user metadata + storage_class: Storage class (standard, infrequent, archive) + + Returns: + UploadResult with object details + """ + try: + # Verify bucket exists and check quota + bucket = await self._verify_bucket(bucket_id) + if not bucket: + return UploadResult(success=False, error="Bucket not found") + + # Check quota + if bucket["quota_bytes"]: + used = bucket.get("used_bytes", 0) + if used + content_length > bucket["quota_bytes"]: + return UploadResult( + success=False, + error=f"Quota exceeded. Available: {bucket['quota_bytes'] - used} bytes" + ) + + # Calculate checksum while reading + md5_hash = hashlib.md5() + sha256_hash = hashlib.sha256() + file_data = bytearray() + + while chunk := data.read(8192): + md5_hash.update(chunk) + sha256_hash.update(chunk) + file_data.extend(chunk) + + etag = md5_hash.hexdigest() + checksum_sha256 = sha256_hash.hexdigest() + + # Get storage nodes via consistent hashing + storage_key = f"{bucket_id}:{object_key}" + node_ids = self.hash_ring.get_nodes(storage_key) + + if not node_ids: + return UploadResult(success=False, error="No storage nodes available") + + # Write to primary node + primary_node = node_ids[0] + file_path = await self.storage.write_file( + node_id=primary_node, + bucket_name=bucket["name"], + object_key=object_key, + data=bytes(file_data) + ) + + # Create object record + async with self.db.acquire() as conn: + object_record = await conn.fetchrow( + """INSERT INTO objects + (bucket_id, object_key, content_type, content_length, + etag, checksum_sha256, storage_class, storage_nodes, + user_metadata, modified_at) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, NOW()) + RETURNING id, version_id, etag""", + bucket_id, + object_key, + content_type or "application/octet-stream", + content_length, + etag, + checksum_sha256, + storage_class, + json.dumps(node_ids), + json.dumps(metadata or {}) + ) + + # Trigger replication to other nodes + await self.replication.replicate_object( + object_id=object_record["id"], + source_node=primary_node, + target_nodes=node_ids[1:] + ) + + # Log upload + await self._log_operation( + bucket_id=bucket_id, + object_id=object_record["id"], + operation="PUT", + bytes_received=content_length, + http_status=201 + ) + + return UploadResult( + success=True, + object_id=object_record["id"], + version_id=object_record["version_id"], + etag=object_record["etag"], + location=f"/{bucket['name']}/{object_key}" + ) + + except Exception as e: + logger.error(f"Upload failed for {object_key}: {e}") + return UploadResult(success=False, error=str(e)) + + async def upload_file_from_path( + self, + bucket_id: int, + object_key: str, + file_path: str, + content_type: str = None, + metadata: Dict[str, Any] = None + ) -> UploadResult: + """Upload a file from local filesystem path.""" + path = Path(file_path) + if not path.exists(): + return UploadResult(success=False, error="File not found") + + content_length = path.stat().st_size + + with open(file_path, "rb") as f: + return await self.upload_file( + bucket_id=bucket_id, + object_key=object_key, + data=f, + content_length=content_length, + content_type=content_type, + metadata=metadata + ) + + async def create_presigned_url( + self, + bucket_id: int, + object_key: str, + operation: str = "put", + expires_in_seconds: int = 3600 + ) -> str: + """ + Create a presigned URL for direct upload/download. + + Client can upload directly to storage node without going through API. + """ + # Verify object exists + async with self.db.acquire() as conn: + if operation == "put": + # For new uploads, verify bucket + bucket = await conn.fetchrow( + "SELECT * FROM buckets WHERE id = $1", + bucket_id + ) + if not bucket: + raise ValueError("Bucket not found") + + object_id = None + else: + # For existing objects + obj = await conn.fetchrow( + """SELECT * FROM objects + WHERE bucket_id = $1 AND object_key = $2 AND is_latest = TRUE""", + bucket_id, object_key + ) + if not obj: + raise ValueError("Object not found") + object_id = obj["id"] + + # Generate presigned URL key + access_key = f"presigned:{uuid.uuid4().hex}" + expires_at = datetime.now(timezone.utc) + timedelta(seconds=expires_in_seconds) + + async with self.db.acquire() as conn: + await conn.execute( + """INSERT INTO presigned_urls + (object_id, access_key, expires_at, operation) + VALUES ($1, $2, $3, $4)""", + object_id, access_key, expires_at, operation + ) + + # Return URL + # In production, this would be your API gateway URL + return f"https://storage.example.com/v1/upload/{access_key}" + + async def verify_presigned_url( + self, + access_key: str, + operation: str + ) -> Optional[Dict[str, Any]]: + """Verify a presigned URL is valid.""" + async with self.db.acquire() as conn: + record = await conn.fetchrow( + """SELECT pu.*, o.bucket_id, o.object_key + FROM presigned_urls pu + LEFT JOIN objects o ON o.id = pu.object_id + WHERE pu.access_key = $1 + AND pu.operation = $2 + AND pu.expires_at > NOW()""", + access_key, operation + ) + + if not record: + return None + + return { + "bucket_id": record["bucket_id"], + "object_key": record["object_key"], + "object_id": record["object_id"], + "operation": record["operation"] + } + + async def get_upload_progress( + self, + upload_id: str + ) -> Optional[UploadProgress]: + """Get progress of an ongoing upload.""" + # For multipart uploads + async with self.db.acquire() as conn: + upload = await conn.fetchrow( + """SELECT mu.*, + (SELECT COUNT(*) FROM multipart_parts mp WHERE mp.upload_id = mu.upload_id) as completed_parts + FROM multipart_uploads mu + WHERE mu.upload_id = $1""", + upload_id + ) + + if not upload: + return None + + total_parts = upload.get("total_parts") or upload["completed_parts"] + 1 + completed = upload["completed_parts"] + + return UploadProgress( + bytes_uploaded=completed * 5 * 1024 * 1024, # Assume 5MB parts + total_bytes=total_parts * 5 * 1024 * 1024, + percentage=(completed / total_parts * 100) if total_parts > 0 else 0, + current_part=completed + 1 + ) + + async def complete_upload( + self, + upload_id: str + ) -> UploadResult: + """Complete a multipart upload.""" + # Implementation in multipart upload subtask + pass + + async def abort_upload( + self, + upload_id: str + ) -> bool: + """Abort a multipart upload.""" + async with self.db.acquire() as conn: + # Get upload info + upload = await conn.fetchrow( + "SELECT * FROM multipart_uploads WHERE upload_id = $1", + upload_id + ) + + if not upload: + return False + + # Delete uploaded parts + await conn.execute( + "DELETE FROM multipart_parts WHERE upload_id = $1", + upload_id + ) + + # Delete upload record + await conn.execute( + "DELETE FROM multipart_uploads WHERE upload_id = $1", + upload_id + ) + + # Clean up files from storage + parts = await conn.fetch( + """SELECT mp.*, o.storage_nodes + FROM multipart_parts mp + JOIN objects o ON o.id = mp.object_id + WHERE mp.upload_id = $1""", + upload_id + ) + + for part in parts: + node_ids = json.loads(part["storage_nodes"]) + for node_id in node_ids: + await self.storage.delete_file( + node_id=node_id, + file_path=str(part["id"]) + ) + + return True + + async def _verify_bucket(self, bucket_id: int) -> Optional[dict]: + """Verify bucket exists and is accessible.""" + async with self.db.acquire() as conn: + return await conn.fetchrow( + "SELECT * FROM buckets WHERE id = $1", + bucket_id + ) + + async def _log_operation( + self, + bucket_id: int = None, + object_id: int = None, + operation: str = None, + user_id: str = None, + bytes_received: int = None, + http_status: int = None, + error_code: str = None + ): + """Log operation to audit table.""" + async with self.db.acquire() as conn: + await conn.execute( + """INSERT INTO audit_log + (bucket_id, object_id, operation, user_id, bytes_received, http_status, error_code) + VALUES ($1, $2, $3, $4, $5, $6, $7)""", + bucket_id, object_id, operation, user_id, bytes_received, http_status, error_code + ) +``` + +**Storage adapter interface**: +```python +from abc import ABC, abstractmethod +from typing import Optional + +class StorageAdapter(ABC): + """Interface for storage backends.""" + + @abstractmethod + async def write_file( + self, + node_id: str, + bucket_name: str, + object_key: str, + data: bytes + ) -> str: + """Write file to storage node. Returns file path.""" + pass + + @abstractmethod + async def read_file( + self, + node_id: str, + file_path: str + ) -> bytes: + """Read file from storage node.""" + pass + + @abstractmethod + async def delete_file( + self, + node_id: str, + file_path: str + ) -> bool: + """Delete file from storage node.""" + pass + + @abstractmethod + async def file_exists( + self, + node_id: str, + file_path: str + ) -> bool: + """Check if file exists on node.""" + pass + + @abstractmethod + async def get_file_info( + self, + node_id: str, + file_path: str + ) -> dict: + """Get file metadata from node.""" + pass +``` + +**Local filesystem storage adapter**: +```python +import aiofiles +import shutil +from pathlib import Path + +class LocalStorageAdapter(StorageAdapter): + """Local filesystem storage adapter.""" + + def __init__(self, base_path: str = "/data/storage"): + self.base_path = Path(base_path) + self.base_path.mkdir(parents=True, exist_ok=True) + + async def write_file( + self, + node_id: str, + bucket_name: str, + object_key: str, + data: bytes + ) -> str: + """Write file to local filesystem.""" + # Create path: /data/storage/{node_id}/{bucket}/{object_key} + file_path = self.base_path / node_id / bucket_name / object_key + file_path.parent.mkdir(parents=True, exist_ok=True) + + async with aiofiles.open(file_path, "wb") as f: + await f.write(data) + + return str(file_path) + + async def read_file(self, node_id: str, file_path: str) -> bytes: + """Read file from local filesystem.""" + async with aiofiles.open(file_path, "rb") as f: + return await f.read() + + async def delete_file(self, node_id: str, file_path: str) -> bool: + """Delete file from local filesystem.""" + path = Path(file_path) + if path.exists(): + path.unlink() + return True + return False + + async def file_exists(self, node_id: str, file_path: str) -> bool: + """Check if file exists.""" + return Path(file_path).exists() + + async def get_file_info(self, node_id: str, file_path: str) -> dict: + """Get file metadata.""" + path = Path(file_path) + if not path.exists(): + return None + + stat = path.stat() + return { + "size": stat.st_size, + "modified": stat.st_mtime, + "created": stat.st_ctime + } +``` + +**Upload API endpoints**: +```python +from fastapi import APIRouter, UploadFile, File, Form, HTTPException, Header +from typing import Optional + +router = APIRouter(prefix="/v1", tags=["upload"]) + +@router.put("/buckets/{bucket_id}/objects/{object_key:path}") +async def upload_object( + bucket_id: int, + object_key: str, + file: UploadFile = File(...), + content_type: Optional[str] = Header(None), + content_md5: Optional[str] = Header(None), + metadata: Optional[str] = Form(None) # JSON string +): + """Upload an object to a bucket.""" + upload_service = get_upload_service() + + # Parse metadata + user_metadata = json.loads(metadata) if metadata else None + + # Read file data + content = await file.read() + content_length = len(content) + + # Verify MD5 if provided + if content_md5: + calculated_md5 = hashlib.md5(content).hexdigest() + if calculated_md5 != content_md5: + raise HTTPException( + status_code=400, + detail=f"MD5 mismatch. Expected: {content_md5}, Got: {calculated_md5}" + ) + + # Create file-like object + from io import BytesIO + data_stream = BytesIO(content) + + # Upload + result = await upload_service.upload_file( + bucket_id=bucket_id, + object_key=object_key, + data=data_stream, + content_length=content_length, + content_type=content_type or file.content_type, + metadata=user_metadata + ) + + if not result.success: + raise HTTPException(status_code=400, detail=result.error) + + return { + "object_id": result.object_id, + "version_id": result.version_id, + "etag": result.etag, + "location": result.location + } + +@router.post("/buckets/{bucket_id}/uploads/presign") +async def create_presigned_upload( + bucket_id: int, + object_key: str, + expires_in: int = 3600 +): + """Create a presigned URL for direct upload.""" + upload_service = get_upload_service() + + url = await upload_service.create_presigned_url( + bucket_id=bucket_id, + object_key=object_key, + operation="put", + expires_in_seconds=expires_in + ) + + return {"upload_url": url, "expires_in": expires_in} + +@router.post("/uploads/presigned/{access_key}") +async def upload_via_presigned_url( + access_key: str, + file: UploadFile = File(...) +): + """Handle presigned URL upload.""" + upload_service = get_upload_service() + + # Verify presigned URL + presigned = await upload_service.verify_presigned_url(access_key, "put") + if not presigned: + raise HTTPException(status_code=403, detail="Invalid or expired presigned URL") + + # Read and upload file + content = await file.read() + + from io import BytesIO + result = await upload_service.upload_file( + bucket_id=presigned["bucket_id"], + object_key=presigned["object_key"], + data=BytesIO(content), + content_length=len(content), + content_type=file.content_type + ) + + if not result.success: + raise HTTPException(status_code=400, detail=result.error) + + return {"etag": result.etag} +``` + +## Acceptance Criteria + +- [ ] Files can be uploaded to buckets +- [ ] MD5 checksum is verified +- [ ] Files are replicated to storage nodes +- [ ] Presigned URLs work for direct uploads +- [ ] Bucket quota is enforced +- [ ] Upload progress is tracked +- [ ] Failed uploads don't leave orphaned files + +## Notes + +**Trade-offs**: +- Streaming vs full read in memory: Streaming for large files +- Direct-to-node vs proxy through API: Presigned URL for direct upload + +**Performance**: +- Use streaming for files > 100MB +- Parallel multipart uploads for large files + +**Alternatives considered**: +- Direct S3 upload: Complex setup +- Tus.io protocol: Overkill for MVP diff --git a/ai_coder_1/subtasks/Decomp-005-03.md b/ai_coder_1/subtasks/Decomp-005-03.md new file mode 100644 index 0000000..4888e5c --- /dev/null +++ b/ai_coder_1/subtasks/Decomp-005-03.md @@ -0,0 +1,709 @@ +# Subtask: Multipart Upload Support + +**Parent Task**: Decomp/005 +**Subtask ID**: Decomp/005-03 +**Dependencies**: Decomp-005-01 (Storage Architecture), Decomp-005-02 (File Upload API) + +## Description + +Implement multipart upload functionality for large files (>100MB). Support parallel part uploads, part assembly, upload resumption, and automatic cleanup of incomplete uploads. + +## Requirements + +- Support multipart uploads for files > 100MB +- Minimum part size: 5MB +- Maximum part size: 5GB +- Maximum 10,000 parts per upload +- Parallel part upload support +- Upload resumption after failure +- Automatic assembly on completion +- Cleanup of expired incomplete uploads +- ETag calculation for each part + +## Technical Specifications + +**Multipart upload manager**: +```python +from typing import List, Dict, Any, Optional, BinaryIO +from dataclasses import dataclass +from datetime import datetime, timezone, timedelta +import hashlib +import uuid +import logging + +logger = logging.getLogger(__name__) + +MIN_PART_SIZE = 5 * 1024 * 1024 # 5MB +MAX_PART_SIZE = 5 * 1024 * 1024 * 1024 # 5GB +MAX_PARTS = 10000 + +@dataclass +class MultipartUploadInfo: + """Information about a multipart upload.""" + upload_id: str + bucket_id: int + object_key: str + owner_id: str + initiated_at: datetime + expires_at: datetime + parts_uploaded: int + total_parts: Optional[int] + metadata: Dict[str, Any] + +@dataclass +class PartInfo: + """Information about an uploaded part.""" + part_number: int + etag: str + size: int + object_id: int + +@dataclass +class CompleteMultipartUploadResult: + """Result of completing multipart upload.""" + success: bool + object_id: int = None + version_id: str = None + location: str = None + etag: str = None + error: str = None + +class MultipartUploadService: + """Service for managing multipart uploads.""" + + def __init__( + self, + db, + upload_service, + storage_adapter + ): + self.db = db + self.upload_service = upload_service + self.storage = storage_adapter + + async def create_multipart_upload( + self, + bucket_id: int, + object_key: str, + content_type: str = None, + metadata: Dict[str, Any] = None, + owner_id: str = None + ) -> str: + """ + Initiate a multipart upload. + + Returns: + upload_id: Unique identifier for this multipart upload + """ + # Generate upload ID + upload_id = f"mpu-{uuid.uuid4().hex}" + + # Set expiration (24 hours) + expires_at = datetime.now(timezone.utc) + timedelta(hours=24) + + async with self.db.acquire() as conn: + await conn.execute( + """INSERT INTO multipart_uploads + (upload_id, bucket_id, object_key, content_type, owner_id, expires_at, metadata) + VALUES ($1, $2, $3, $4, $5, $6, $7)""", + upload_id, + bucket_id, + object_key, + content_type or "application/octet-stream", + owner_id, + expires_at, + json.dumps(metadata or {}) + ) + + logger.info(f"Created multipart upload {upload_id} for {object_key}") + return upload_id + + async def upload_part( + self, + upload_id: str, + part_number: int, + data: BinaryIO, + content_length: int + ) -> PartInfo: + """ + Upload a single part of a multipart upload. + + Args: + upload_id: Multipart upload ID + part_number: Part number (1-indexed) + data: Part data + content_length: Size of part in bytes + + Returns: + PartInfo with etag and storage details + """ + # Validate part number + if part_number < 1 or part_number > MAX_PARTS: + raise ValueError(f"Part number must be 1-{MAX_PARTS}") + + # Validate part size + if content_length < MIN_PART_SIZE: + # Exception: Last part can be smaller + # We'll check this on completion + pass + elif content_length > MAX_PART_SIZE: + raise ValueError(f"Part size exceeds maximum of {MAX_PART_SIZE} bytes") + + # Verify upload exists and not expired + async with self.db.acquire() as conn: + upload = await conn.fetchrow( + """SELECT * FROM multipart_uploads + WHERE upload_id = $1 AND expires_at > NOW()""", + upload_id + ) + + if not upload: + raise ValueError("Upload not found or expired") + + # Check if part already exists + existing = await conn.fetchrow( + """SELECT mp.*, o.bucket_id, o.object_key + FROM multipart_parts mp + JOIN objects o ON o.id = mp.object_id + WHERE mp.upload_id = $1 AND mp.part_number = $2""", + upload_id, part_number + ) + + if existing: + # Part already uploaded, return existing + return PartInfo( + part_number=part_number, + etag=existing["etag"], + size=existing["size_bytes"], + object_id=existing["object_id"] + ) + + # Calculate checksum + md5_hash = hashlib.md5() + file_data = bytearray() + + while chunk := data.read(8192): + md5_hash.update(chunk) + file_data.extend(chunk) + + etag = md5_hash.hexdigest() + + # Store part as a temporary object + # Use a special key to identify it as a multipart part + part_key = f".multipart/{upload_id}/part-{part_number}" + + from io import BytesIO + result = await self.upload_service.upload_file( + bucket_id=upload["bucket_id"], + object_key=part_key, + data=BytesIO(bytes(file_data)), + content_length=content_length, + content_type=upload.get("content_type") + ) + + if not result.success: + raise Exception(f"Failed to upload part: {result.error}") + + # Record part + async with self.db.acquire() as conn: + await conn.execute( + """INSERT INTO multipart_parts + (upload_id, part_number, object_id, size_bytes, etag) + VALUES ($1, $2, $3, $4, $5)""", + upload_id, + part_number, + result.object_id, + content_length, + etag + ) + + # Update parts count + await conn.execute( + """UPDATE multipart_uploads + SET parts_uploaded = ( + SELECT COUNT(*) FROM multipart_parts WHERE upload_id = $1 + ) + WHERE upload_id = $1""", + upload_id + ) + + logger.info(f"Uploaded part {part_number} of upload {upload_id}") + + return PartInfo( + part_number=part_number, + etag=etag, + size=content_length, + object_id=result.object_id + ) + + async def complete_multipart_upload( + self, + upload_id: str, + parts: List[Dict[str, Any]] # [{part_number, etag}] + ) -> CompleteMultipartUploadResult: + """ + Complete a multipart upload by assembling parts. + + Args: + upload_id: Multipart upload ID + parts: List of parts with part_number and etag + + Returns: + CompleteMultipartUploadResult with final object details + """ + async with self.db.acquire() as conn: + # Get upload info + upload = await conn.fetchrow( + """SELECT mu.*, b.name as bucket_name + FROM multipart_uploads mu + JOIN buckets b ON b.id = mu.bucket_id + WHERE mu.upload_id = $1""", + upload_id + ) + + if not upload: + return CompleteMultipartUploadResult( + success=False, + error="Upload not found or expired" + ) + + # Verify all parts present + uploaded_parts = await conn.fetch( + """SELECT mp.* FROM multipart_parts mp + WHERE mp.upload_id = $1 + ORDER BY mp.part_number""", + upload_id + ) + + part_map = {p["part_number"]: p for p in uploaded_parts} + + # Verify client provided parts match + for part in parts: + if part["part_number"] not in part_map: + return CompleteMultipartUploadResult( + success=False, + error=f"Part {part['part_number']} not uploaded" + ) + if part_map[part["part_number"]]["etag"] != part["etag"]: + return CompleteMultipartUploadResult( + success=False, + error=f"ETag mismatch for part {part['part_number']}" + ) + + # Sort parts and assemble + sorted_parts = sorted(uploaded_parts, key=lambda p: p["part_number"]) + + # Calculate total size and composite ETag + total_size = sum(p["size_bytes"] for p in sorted_parts) + + # Composite ETag: MD5 of all part ETags concatenated + etags = "-".join(p["etag"] for p in sorted_parts) + composite_etag = hashlib.md5(etags.encode()).hexdigest() + "-" + str(len(sorted_parts)) + + # Get storage nodes + storage_key = f"{upload['bucket_id']}:{upload['object_key']}" + node_ids = self.upload_service.hash_ring.get_nodes(storage_key) + + # Assemble file on primary node + primary_node = node_ids[0] + + # Read all parts and combine + assembled_data = bytearray() + for part in sorted_parts: + # Read part data from storage + part_path = await conn.fetchval( + """SELECT o.storage_nodes->>0 as node_id, + (o.storage_nodes->>0) || ':' || + o.bucket_id || ':' || + o.object_key as file_key + FROM objects o + WHERE o.id = $1""", + part["object_id"] + ) + + part_data = await self.storage.read_file( + node_id=primary_node, + file_path=f"{upload['bucket_name']}/.multipart/{upload_id}/part-{part['part_number']}" + ) + assembled_data.extend(part_data) + + # Write assembled file + final_path = await self.storage.write_file( + node_id=primary_node, + bucket_name=upload["bucket_name"], + object_key=upload["object_key"], + data=bytes(assembled_data) + ) + + # Create final object record + metadata = json.loads(upload.get("metadata", "{}")) + object_record = await conn.fetchrow( + """INSERT INTO objects + (bucket_id, object_key, content_type, content_length, + etag, storage_class, storage_nodes, user_metadata) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8) + RETURNING id, version_id""", + upload["bucket_id"], + upload["object_key"], + upload.get("content_type", "application/octet-stream"), + total_size, + composite_etag, + "standard", + json.dumps(node_ids), + json.dumps(metadata) + ) + + # Trigger replication + await self.upload_service.replication.replicate_object( + object_id=object_record["id"], + source_node=primary_node, + target_nodes=node_ids[1:] + ) + + # Clean up multipart upload + await self._cleanup_multipart_upload(conn, upload_id) + + logger.info( + f"Completed multipart upload {upload_id} " + f"-> object {object_record['id']} ({len(sorted_parts)} parts)" + ) + + return CompleteMultipartUploadResult( + success=True, + object_id=object_record["id"], + version_id=object_record["version_id"], + location=f"/{upload['bucket_name']}/{upload['object_key']}", + etag=composite_etag + ) + + async def abort_multipart_upload( + self, + upload_id: str + ) -> bool: + """Abort a multipart upload and clean up all parts.""" + async with self.db.acquire() as conn: + upload = await conn.fetchrow( + """SELECT mu.*, b.name as bucket_name + FROM multipart_uploads mu + JOIN buckets b ON b.id = mu.bucket_id + WHERE mu.upload_id = $1""", + upload_id + ) + + if not upload: + return False + + await self._cleanup_multipart_upload(conn, upload_id) + return True + + async def _cleanup_multipart_upload(self, conn, upload_id: str): + """Clean up all resources for a multipart upload.""" + # Get all parts + parts = await conn.fetch( + """SELECT mp.*, o.storage_nodes, o.object_key, b.name as bucket_name + FROM multipart_parts mp + JOIN objects o ON o.id = mp.object_id + JOIN buckets b ON b.id = o.bucket_id + WHERE mp.upload_id = $1""", + upload_id + ) + + # Delete part files from storage + for part in parts: + node_ids = json.loads(part["storage_nodes"]) + for node_id in node_ids: + part_path = f"{part['bucket_name']}/.multipart/{upload_id}/part-{part['part_number']}" + await self.storage.delete_file(node_id=node_id, file_path=part_path) + + # Delete part objects + await conn.execute( + """DELETE FROM objects + WHERE id IN (SELECT object_id FROM multipart_parts WHERE upload_id = $1)""", + upload_id + ) + + # Delete multipart parts records + await conn.execute( + "DELETE FROM multipart_parts WHERE upload_id = $1", + upload_id + ) + + # Delete upload record + await conn.execute( + "DELETE FROM multipart_uploads WHERE upload_id = $1", + upload_id + ) + + logger.info(f"Cleaned up multipart upload {upload_id}") + + async def list_parts( + self, + upload_id: str, + max_parts: int = 1000, + part_number_marker: int = 0 + ) -> List[PartInfo]: + """List uploaded parts for a multipart upload.""" + async with self.db.acquire() as conn: + parts = await conn.fetch( + """SELECT mp.* + FROM multipart_parts mp + WHERE mp.upload_id = $1 AND mp.part_number > $2 + ORDER BY mp.part_number + LIMIT $3""", + upload_id, part_number_marker, max_parts + ) + + return [ + PartInfo( + part_number=p["part_number"], + etag=p["etag"], + size=p["size_bytes"], + object_id=p["object_id"] + ) + for p in parts + ] + + async def list_multipart_uploads( + self, + bucket_id: int, + max_uploads: int = 1000, + key_marker: str = None, + upload_id_marker: str = None + ) -> List[MultipartUploadInfo]: + """List in-progress multipart uploads.""" + async with self.db.acquire() as conn: + query = """ + SELECT mu.* FROM multipart_uploads mu + WHERE mu.bucket_id = $1 + AND mu.expires_at > NOW() + """ + params = [bucket_id] + + if key_marker: + query += " AND mu.object_key > $2" + params.append(key_marker) + elif upload_id_marker: + query += " AND mu.upload_id > $" + str(len(params) + 1) + params.append(upload_id_marker) + + query += " ORDER BY mu.object_key, mu.initiated_at" + query += f" LIMIT ${len(params) + 1}" + params.append(max_uploads) + + uploads = await conn.fetch(query, *params) + + return [ + MultipartUploadInfo( + upload_id=u["upload_id"], + bucket_id=u["bucket_id"], + object_key=u["object_key"], + owner_id=u["owner_id"], + initiated_at=u["initiated_at"], + expires_at=u["expires_at"], + parts_uploaded=u["parts_uploaded"], + total_parts=u.get("total_parts"), + metadata=json.loads(u.get("metadata", "{}")) + ) + for u in uploads + ] + + async def cleanup_expired_uploads(self) -> int: + """Clean up expired multipart uploads (background task).""" + async with self.db.acquire() as conn: + # Find expired uploads + expired = await conn.fetch( + """SELECT upload_id FROM multipart_uploads + WHERE expires_at < NOW()""" + ) + + cleaned = 0 + for upload in expired: + await self._cleanup_multipart_upload(conn, upload["upload_id"]) + cleaned += 1 + + if cleaned > 0: + logger.info(f"Cleaned up {cleaned} expired multipart uploads") + + return cleaned +``` + +**Multipart upload API**: +```python +from fastapi import APIRouter, HTTPException, UploadFile, File, Form, Query +from typing import List, Optional +from pydantic import BaseModel + +router = APIRouter(prefix="/v1/multipart", tags=["multipart"]) + +class PartModel(BaseModel): + part_number: int + etag: str + +class CompleteMultipartUploadModel(BaseModel): + parts: List[PartModel] + +@router.post("/uploads/{bucket_id}/{object_key:path}") +async def create_multipart_upload( + bucket_id: int, + object_key: str, + content_type: Optional[str] = None, + metadata: Optional[str] = None, # JSON string + owner_id: Optional[str] = None +): + """Initiate a multipart upload.""" + service = get_multipart_service() + + user_metadata = json.loads(metadata) if metadata else None + + upload_id = await service.create_multipart_upload( + bucket_id=bucket_id, + object_key=object_key, + content_type=content_type, + metadata=user_metadata, + owner_id=owner_id + ) + + return {"upload_id": upload_id} + +@router.put("/uploads/{upload_id}/parts/{part_number}") +async def upload_part( + upload_id: str, + part_number: int, + file: UploadFile = File(...) +): + """Upload a part.""" + service = get_multipart_service() + + content = await file.read() + + from io import BytesIO + part_info = await service.upload_part( + upload_id=upload_id, + part_number=part_number, + data=BytesIO(content), + content_length=len(content) + ) + + return { + "part_number": part_info.part_number, + "etag": part_info.etag, + "size": part_info.size + } + +@router.post("/uploads/{upload_id}/complete") +async def complete_multipart_upload( + upload_id: str, + data: CompleteMultipartUploadModel +): + """Complete a multipart upload.""" + service = get_multipart_service() + + result = await service.complete_multipart_upload( + upload_id=upload_id, + parts=[{"part_number": p.part_number, "etag": p.etag} for p in data.parts] + ) + + if not result.success: + raise HTTPException(status_code=400, detail=result.error) + + return { + "object_id": result.object_id, + "version_id": result.version_id, + "location": result.location, + "etag": result.etag + } + +@router.delete("/uploads/{upload_id}") +async def abort_multipart_upload(upload_id: str): + """Abort a multipart upload.""" + service = get_multipart_service() + + success = await service.abort_multipart_upload(upload_id) + + if not success: + raise HTTPException(status_code=404, detail="Upload not found") + + return {"message": "Upload aborted"} + +@router.get("/uploads/{upload_id}/parts") +async def list_upload_parts( + upload_id: str, + max_parts: int = Query(1000), + part_number_marker: int = Query(0) +): + """List parts of a multipart upload.""" + service = get_multipart_service() + + parts = await service.list_parts( + upload_id=upload_id, + max_parts=max_parts, + part_number_marker=part_number_marker + ) + + return { + "upload_id": upload_id, + "parts": [ + { + "part_number": p.part_number, + "etag": p.etag, + "size": p.size + } + for p in parts + ] + } + +@router.get("/uploads/{bucket_id}") +async def list_multipart_uploads( + bucket_id: int, + max_uploads: int = Query(1000), + key_marker: str = None, + upload_id_marker: str = None +): + """List in-progress multipart uploads.""" + service = get_multipart_service() + + uploads = await service.list_multipart_uploads( + bucket_id=bucket_id, + max_uploads=max_uploads, + key_marker=key_marker, + upload_id_marker=upload_id_marker + ) + + return { + "bucket_id": bucket_id, + "uploads": [ + { + "upload_id": u.upload_id, + "object_key": u.object_key, + "initiated_at": u.initiated_at.isoformat(), + "parts_uploaded": u.parts_uploaded, + "owner_id": u.owner_id + } + for u in uploads + ] + } +``` + +## Acceptance Criteria + +- [ ] Multipart uploads can be initiated +- [ ] Parts can be uploaded in parallel +- [ ] Parts are validated on completion +- [ ] Completed uploads are assembled correctly +- [ ] Aborted uploads are cleaned up +- [ ] Expired uploads are auto-cleaned +- [ ] Composite ETag is calculated correctly + +## Notes + +**Trade-offs**: +- In-memory vs streaming assembly: Streaming for very large files +- Synchronous vs asynchronous part assembly: Synchronous simpler + +**Performance**: +- Use parallel uploads for parts +- Cache part metadata during upload + +**Alternatives considered**: +- S3 multipart upload API: Similar approach adopted +- Chunked transfer encoding: Less flexible diff --git a/ai_coder_1/subtasks/Decomp-005-04.md b/ai_coder_1/subtasks/Decomp-005-04.md new file mode 100644 index 0000000..83db428 --- /dev/null +++ b/ai_coder_1/subtasks/Decomp-005-04.md @@ -0,0 +1,654 @@ +# Subtask: Data Replication Engine + +**Parent Task**: Decomp/005 +**Subtask ID**: Decomp-005-04 +**Dependencies**: Decomp-005-01 (Storage Architecture), Decomp-005-02 (File Upload API) + +## Description + +Implement asynchronous replication engine for data durability. Support configurable replication factor, conflict resolution, node failure handling, and replication status tracking. + +## Requirements + +- Replicate objects to N nodes +- Asynchronous replication for performance +- Replication status tracking +- Handle node failures gracefully +- Re-replicate when nodes come back online +- Anti-entropy for consistency verification +- Prioritize critical data replication + +## Technical Specifications + +**Replication engine**: +```python +from typing import List, Dict, Any, Optional, Set +from dataclasses import dataclass, field +from datetime import datetime, timezone, timedelta +from enum import Enum +import asyncio +import logging + +logger = logging.getLogger(__name__) + +class ReplicationStatus(Enum): + """Replication status.""" + PENDING = "pending" + IN_PROGRESS = "in_progress" + COMPLETED = "completed" + FAILED = "failed" + +@dataclass +class ReplicationTask: + """A replication task for an object.""" + object_id: int + source_node: str + target_nodes: Set[str] + priority: int = 5 # 1=highest, 10=lowest + retry_count: int = 0 + max_retries: int = 3 + created_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc)) + +@dataclass +class ReplicationResult: + """Result of replication attempt.""" + object_id: int + success: bool + completed_nodes: List[str] + failed_nodes: List[str] + error: str = None + +class ReplicationEngine: + """Engine for managing data replication across storage nodes.""" + + def __init__( + self, + db, + storage_adapter, + replication_factor: int = 3, + max_concurrent: int = 10 + ): + self.db = db + self.storage = storage_adapter + self.replication_factor = replication_factor + self.max_concurrent = max_concurrent + + # Task queues + self.pending_queue: asyncio.Queue[ReplicationTask] = asyncio.Queue() + self.in_progress: Dict[int, ReplicationTask] = {} + self.worker_tasks: List[asyncio.Task] = [] + + # Statistics + self.stats = { + "replicated": 0, + "failed": 0, + "bytes_replicated": 0, + "start_time": datetime.now(timezone.utc) + } + + async def start(self): + """Start replication workers.""" + for i in range(self.max_concurrent): + task = asyncio.create_task(self._worker(f"worker-{i}")) + self.worker_tasks.append(task) + + logger.info(f"Started {self.max_concurrent} replication workers") + + async def stop(self): + """Stop replication workers.""" + for task in self.worker_tasks: + task.cancel() + + await asyncio.gather(*self.worker_tasks, return_exceptions=True) + self.worker_tasks.clear() + + logger.info("Stopped replication workers") + + async def replicate_object( + self, + object_id: int, + source_node: str, + target_nodes: List[str], + priority: int = 5 + ) -> str: + """ + Queue object for replication. + + Returns: + replication_id for tracking + """ + task = ReplicationTask( + object_id=object_id, + source_node=source_node, + target_nodes=set(target_nodes), + priority=priority + ) + + # Record in database + async with self.db.acquire() as conn: + for target_node in target_nodes: + await conn.execute( + """INSERT INTO replication_status + (object_id, source_node, target_node, status, started_at) + VALUES ($1, $2, $3, 'pending', NOW())""", + object_id, source_node, target_node + ) + + await self.pending_queue.put(task) + logger.info(f"Queued replication for object {object_id} to {len(target_nodes)} nodes") + + return f"replication-{object_id}-{datetime.now().timestamp()}" + + async def get_replication_status( + self, + object_id: int + ) -> Dict[str, Any]: + """Get replication status for an object.""" + async with self.db.acquire() as conn: + rows = await conn.fetch( + """SELECT rs.* + FROM replication_status rs + WHERE rs.object_id = $1 + ORDER BY rs.target_node""", + object_id + ) + + completed = sum(1 for r in rows if r["status"] == "completed") + failed = sum(1 for r in rows if r["status"] == "failed") + pending = sum(1 for r in rows if r["status"] in ("pending", "in_progress")) + + return { + "object_id": object_id, + "total": len(rows), + "completed": completed, + "failed": failed, + "pending": pending, + "is_fully_replicated": completed >= self.replication_factor - 1, + "details": [ + { + "target_node": r["target_node"], + "status": r["status"], + "started_at": r["started_at"].isoformat() if r["started_at"] else None, + "completed_at": r["completed_at"].isoformat() if r["completed_at"] else None, + "error": r["error_message"] + } + for r in rows + ] + } + + async def _worker(self, worker_name: str): + """Worker that processes replication tasks.""" + logger.info(f"Replication worker {worker_name} started") + + while True: + try: + task = await asyncio.wait_for( + self.pending_queue.get(), + timeout=1.0 + ) + + result = await self._execute_replication(task) + + if result.success: + self.stats["replicated"] += 1 + else: + self.stats["failed"] += 1 + + except asyncio.TimeoutError: + continue + except asyncio.CancelledError: + break + except Exception as e: + logger.error(f"Worker {worker_name} error: {e}") + await asyncio.sleep(1) + + async def _execute_replication( + self, + task: ReplicationTask + ) -> ReplicationResult: + """Execute replication for a task.""" + self.in_progress[task.object_id] = task + + try: + # Get object details + async with self.db.acquire() as conn: + obj = await conn.fetchrow( + """SELECT o.*, b.name as bucket_name + FROM objects o + JOIN buckets b ON b.id = o.bucket_id + WHERE o.id = $1""", + task.object_id + ) + + if not obj: + return ReplicationResult( + object_id=task.object_id, + success=False, + completed_nodes=[], + failed_nodes=list(task.target_nodes), + error="Object not found" + ) + + # Read from source node + source_path = f"{obj['bucket_name']}/{obj['object_key']}" + + source_data = await self.storage.read_file( + node_id=task.source_node, + file_path=source_path + ) + + self.stats["bytes_replicated"] += len(source_data) + + # Replicate to each target node + completed = [] + failed = [] + + for target_node in task.target_nodes: + try: + # Write to target node + await self.storage.write_file( + node_id=target_node, + bucket_name=obj["bucket_name"], + object_key=obj["object_key"], + data=source_data + ) + + # Update status + async with self.db.acquire() as conn: + await conn.execute( + """UPDATE replication_status + SET status = 'completed', completed_at = NOW() + WHERE object_id = $1 AND target_node = $2""", + task.object_id, target_node + ) + + completed.append(target_node) + logger.debug(f"Replicated object {task.object_id} to {target_node}") + + except Exception as e: + failed.append(target_node) + logger.error(f"Failed to replicate to {target_node}: {e}") + + # Update failure status + async with self.db.acquire() as conn: + await conn.execute( + """UPDATE replication_status + SET status = 'failed', + error_message = $1, + completed_at = NOW() + WHERE object_id = $2 AND target_node = $3""", + str(e), task.object_id, target_node + ) + + success = len(completed) >= len(task.target_nodes) - 1 # Allow 1 failure + + return ReplicationResult( + object_id=task.object_id, + success=success, + completed_nodes=completed, + failed_nodes=failed, + error=f"Failed to replicate to {len(failed)} nodes" if failed else None + ) + + finally: + self.in_progress.pop(task.object_id, None) + + async def check_replication_health(self) -> Dict[str, Any]: + """Check health of replication across all objects.""" + async with self.db.acquire() as conn: + # Find under-replicated objects + under_replicated = await conn.fetch( + """SELECT o.id, o.bucket_id, o.object_key, + COUNT(rs.id) FILTER (WHERE rs.status = 'completed') as replicas + FROM objects o + LEFT JOIN replication_status rs ON rs.object_id = o.id + GROUP BY o.id + HAVING COUNT(rs.id) FILTER (WHERE rs.status = 'completed') < $1 + LIMIT 100""", + self.replication_factor - 1 + ) + + # Get node health + nodes = await conn.fetch( + """SELECT node_id, status, + COUNT(rs.id) FILTER (WHERE rs.status = 'in_progress') as active_replications + FROM storage_nodes sn + LEFT JOIN replication_status rs ON rs.target_node = sn.node_id AND rs.status = 'in_progress' + GROUP BY sn.node_id, sn.status""" + ) + + return { + "under_replicated_objects": len(under_replicated), + "replication_factor": self.replication_factor, + "worker_stats": self.stats, + "nodes": [ + { + "node_id": n["node_id"], + "status": n["status"], + "active_replications": n["active_replications"] + } + for n in nodes + ] + } + + async def re_replicate_objects(self, limit: int = 100) -> int: + """ + Find and re-replicate under-replicated objects. + + Should be run periodically. + """ + async with self.db.acquire() as conn: + # Find objects that need re-replication + objects = await conn.fetch( + """SELECT o.id, o.storage_nodes + FROM objects o + WHERE o.created_at > NOW() - INTERVAL '7 days' + LIMIT $1""", + limit + ) + + re_replicated = 0 + + for obj in objects: + object_id = obj["id"] + current_nodes = set(json.loads(obj.get("storage_nodes", "[]"))) + + # Check if all nodes are still available + available_nodes = await conn.fetch( + """SELECT node_id FROM storage_nodes + WHERE status = 'active'""" + ) + + available_set = {n["node_id"] for n in available_nodes} + missing_nodes = available_set - current_nodes + + if missing_nodes: + # Get a healthy source node + source_node = next((n for n in current_nodes if n in available_set), None) + + if source_node: + # Queue re-replication + new_nodes = list(missing_nodes)[:self.replication_factor - len(current_nodes)] + + if new_nodes: + await self.replicate_object( + object_id=object_id, + source_node=source_node, + target_nodes=new_nodes, + priority=3 # Higher priority for re-replication + ) + re_replicated += 1 + + if re_replicated > 0: + logger.info(f"Re-replicated {re_replicated} objects") + + return re_replicated + + async def anti_entropy_scan( + self, + bucket_id: int = None, + sample_size: int = 1000 + ) -> Dict[str, Any]: + """ + Perform anti-entropy scan to verify replication consistency. + + Compares checksums across replicas. + """ + async with self.db.acquire() as conn: + # Sample objects + query = "SELECT o.* FROM objects o" + params = [] + + if bucket_id: + query += " WHERE o.bucket_id = $1" + params.append(bucket_id) + + query += f" ORDER BY RANDOM() LIMIT ${len(params) + 1}" + params.append(sample_size) + + objects = await conn.fetch(query, *params) + + inconsistencies = [] + + for obj in objects: + storage_nodes = json.loads(obj.get("storage_nodes", "[]")) + + if len(storage_nodes) < 2: + continue # Skip single-replica objects + + # Check checksums on each replica + checksums = {} + for node_id in storage_nodes: + try: + file_info = await self.storage.get_file_info( + node_id=node_id, + file_path=f"{obj.get('bucket_name')}/{obj['object_key']}" + ) + checksums[node_id] = file_info.get("checksum") + except Exception as e: + logger.warning(f"Could not read {obj['id']} from {node_id}: {e}") + + # Check if all checksums match + unique_checksums = set(checksums.values()) + + if len(unique_checksums) > 1: + inconsistencies.append({ + "object_id": obj["id"], + "object_key": obj["object_key"], + "checksums": checksums + }) + + # Trigger re-replication from primary + primary_node = storage_nodes[0] + await self.replicate_object( + object_id=obj["id"], + source_node=primary_node, + target_nodes=storage_nodes[1:], + priority=2 # High priority + ) + + return { + "sample_size": len(objects), + "inconsistencies_found": len(inconsistencies), + "inconsistencies": inconsistencies[:10] # Return first 10 + } + + async def handle_node_failure(self, failed_node: str): + """ + Handle a node failure by marking its replicas for re-replication. + + Called when a node goes offline. + """ + logger.warning(f"Handling node failure: {failed_node}") + + async with self.db.acquire() as conn: + # Find all objects on this node + objects = await conn.fetch( + """SELECT DISTINCT o.id, o.storage_nodes + FROM objects o + WHERE o.storage_nodes @> $1::jsonb + LIMIT 10000""", + json.dumps([failed_node]) + ) + + re_replicated = 0 + + for obj in objects: + object_id = obj["id"] + current_nodes = set(json.loads(obj["storage_nodes"])) + + # Remove failed node + current_nodes.discard(failed_node) + + if len(current_nodes) < self.replication_factor: + # Get available nodes + available = await conn.fetch( + """SELECT node_id FROM storage_nodes + WHERE status = 'active' + AND node_id != $1 + LIMIT 10""", + failed_node + ) + + available_nodes = [a["node_id"] for a in available] + + # Select new replicas + needed = self.replication_factor - len(current_nodes) + new_nodes = available_nodes[:needed] + + if new_nodes and current_nodes: + # Queue re-replication + await self.replicate_object( + object_id=object_id, + source_node=list(current_nodes)[0], + target_nodes=new_nodes, + priority=1 # Highest priority + ) + re_replicated += 1 + + logger.info(f"Queued {re_replicated} objects for re-replication after node {failed_node} failure") + + return re_replicated +``` + +**Node health monitor**: +```python +class NodeHealthMonitor: + """Monitor storage node health and trigger re-replication.""" + + def __init__( + self, + db, + replication_engine: ReplicationEngine, + heartbeat_timeout: int = 60 + ): + self.db = db + self.replication = replication_engine + self.heartbeat_timeout = heartbeat_timeout + self.task: Optional[asyncio.Task] = None + + async def start(self): + """Start health monitoring.""" + self.task = asyncio.create_task(self._monitor_loop()) + logger.info("Node health monitor started") + + async def stop(self): + """Stop health monitoring.""" + if self.task: + self.task.cancel() + try: + await self.task + except asyncio.CancelledError: + pass + + logger.info("Node health monitor stopped") + + async def _monitor_loop(self): + """Monitor node health continuously.""" + while True: + try: + await self._check_node_health() + await asyncio.sleep(30) # Check every 30 seconds + except asyncio.CancelledError: + break + except Exception as e: + logger.error(f"Health monitor error: {e}") + await asyncio.sleep(30) + + async def _check_node_health(self): + """Check health of all storage nodes.""" + async with self.db.acquire() as conn: + # Find nodes with stale heartbeats + failed_nodes = await conn.fetch( + """SELECT node_id, status + FROM storage_nodes + WHERE last_heartbeat < NOW() - INTERVAL '1 second' * $1 + AND status = 'active'""", + self.heartbeat_timeout + ) + + # Find nodes that are back online + recovered_nodes = await conn.fetch( + """SELECT node_id, status + FROM storage_nodes + WHERE last_heartbeat >= NOW() - INTERVAL '1 second' * $1 + AND status IN ('offline', 'maintenance')""", + self.heartbeat_timeout + ) + + # Handle failures + for node in failed_nodes: + logger.warning(f"Node {node['node_id']} appears to be down") + await conn.execute( + "UPDATE storage_nodes SET status = 'offline' WHERE node_id = $1", + node["node_id"] + ) + await self.replication.handle_node_failure(node["node_id"]) + + # Handle recoveries + for node in recovered_nodes: + logger.info(f"Node {node['node_id']} is back online") + await conn.execute( + "UPDATE storage_nodes SET status = 'active' WHERE node_id = $1", + node["node_id"] + ) +``` + +**Replication metrics API**: +```python +from fastapi import APIRouter + +router = APIRouter(prefix="/v1/replication", tags=["replication"]) + +@router.get("/health") +async def replication_health(): + """Get replication health status.""" + replication = get_replication_engine() + return await replication.check_replication_health() + +@router.get("/objects/{object_id}/status") +async def object_replication_status(object_id: int): + """Get replication status for an object.""" + replication = get_replication_engine() + return await replication.get_replication_status(object_id) + +@router.post("/re-replicate") +async def trigger_re_replication(limit: int = 100): + """Trigger re-replication of under-replicated objects.""" + replication = get_replication_engine() + count = await replication.re_replicate_objects(limit) + return {"re_replicated": count} + +@router.post("/anti-entropy") +async def run_anti_entropy_scan( + bucket_id: Optional[int] = None, + sample_size: int = 1000 +): + """Run anti-entropy scan to verify data consistency.""" + replication = get_replication_engine() + return await replication.anti_entropy_scan(bucket_id, sample_size) +``` + +## Acceptance Criteria + +- [ ] Objects are replicated to N nodes +- [ ] Replication status is tracked +- [ ] Failed nodes trigger re-replication +- [ ] Anti-entropy scan detects inconsistencies +- [ ] Node failures are handled gracefully +- [ ] Workers process replication queue +- [ ] Health monitoring works correctly + +## Notes + +**Trade-offs**: +- Synchronous vs asynchronous replication: Async for upload performance +- Strong vs eventual consistency: Eventual with verification + +**Performance**: +- Use connection pooling for storage nodes +- Prioritize critical data replication + +**Alternatives considered**: +- Raft consensus: Overkill for this use case +- Chain replication: Slower recovery time diff --git a/ai_coder_1/subtasks/Decomp-005-05.md b/ai_coder_1/subtasks/Decomp-005-05.md new file mode 100644 index 0000000..09cefdd --- /dev/null +++ b/ai_coder_1/subtasks/Decomp-005-05.md @@ -0,0 +1,780 @@ +# Subtask: Access Control System + +**Parent Task**: Decomp/005 +**Subtask ID**: Decomp-005-05 +**Dependencies**: Decomp-005-01 (Storage Architecture) + +## Description + +Implement access control system for buckets and objects. Support ACLs (Access Control Lists), presigned URLs with limited permissions, bucket policies, and authentication/authorization. + +## Requirements + +- Bucket-level access control +- Object-level ACLs +- Permission types: read, write, delete, list +- User and group-based grants +- Public access support +- Presigned URL authentication +- Policy validation and enforcement +- Access logging + +## Technical Specifications + +**Permission definitions**: +```python +from enum import Enum +from typing import List, Dict, Any, Optional, Set +from dataclasses import dataclass +from datetime import datetime, timezone +import logging + +logger = logging.getLogger(__name__) + +class Permission(Enum): + """Permission types.""" + READ = "read" + WRITE = "write" + DELETE = "delete" + LIST = "list" + READ_ACL = "read_acl" # Read ACL permissions + WRITE_ACL = "write_acl" # Write ACL permissions + FULL_CONTROL = "full_control" + +class GranteeType(Enum): + """Types of grantees.""" + USER = "user" # Specific user ID + GROUP = "group" # User group + ALL = "all" # Public (everyone) + AUTHENTICATED = "authenticated" # Any authenticated user + +@dataclass +class Grant: + """An access control grant.""" + grantee_type: GranteeType + grantee_id: Optional[str] # None for ALL/AUTHENTICATED + permission: Permission + resource_type: str # 'bucket' or 'object' + resource_id: int + +@dataclass +class AccessPolicy: + """Access policy for a resource.""" + resource_type: str + resource_id: int + owner_id: str + public_read: bool = False + grants: List[Grant] = None + + def __post_init__(self): + if self.grants is None: + self.grants = [] +``` + +**Access control service**: +```python +class AccessControlService: + """Service for managing access control.""" + + def __init__(self, db): + self.db = db + + async def check_permission( + self, + user_id: str, + resource_type: str, + resource_id: int, + required_permission: Permission + ) -> bool: + """ + Check if user has permission on a resource. + + Args: + user_id: User ID (or None for anonymous) + resource_type: 'bucket' or 'object' + resource_id: Bucket or object ID + required_permission: Permission being checked + + Returns: + True if user has permission + """ + # Get resource owner + async with self.db.acquire() as conn: + if resource_type == "bucket": + owner = await conn.fetchval( + "SELECT owner_id FROM buckets WHERE id = $1", + resource_id + ) + else: + owner = await conn.fetchval( + """SELECT b.owner_id + FROM objects o + JOIN buckets b ON b.id = o.bucket_id + WHERE o.id = $1""", + resource_id + ) + + # Owner has full control + if owner and user_id == owner: + return True + + # Check public access first + if await self._has_public_access(conn, resource_type, resource_id, required_permission): + return True + + # No user = only check public access + if not user_id: + return False + + # Check user's direct grants + if await self._check_grant(conn, user_id, resource_type, resource_id, required_permission): + return True + + # Check group memberships + if await self._check_group_grants(conn, user_id, resource_type, resource_id, required_permission): + return True + + # Check bucket policy for objects + if resource_type == "object": + bucket_id = await conn.fetchval( + "SELECT bucket_id FROM objects WHERE id = $1", + resource_id + ) + if bucket_id and await self._check_bucket_policy(conn, bucket_id, required_permission): + return True + + return False + + async def _has_public_access( + self, + conn, + resource_type: str, + resource_id: int, + permission: Permission + ) -> bool: + """Check if resource allows public access.""" + # Check for public grants + public_grants = await conn.fetchval( + """SELECT EXISTS( + SELECT 1 FROM acls + WHERE resource_type = $1 + AND resource_id = $2 + AND grantee_type = 'all' + AND permission = $3 + )""", + resource_type, resource_id, permission.value + ) + + return public_grants + + async def _check_grant( + self, + conn, + user_id: str, + resource_type: str, + resource_id: int, + required_permission: Permission + ) -> bool: + """Check direct user grants.""" + # Check for FULL_CONTROL first + has_full_control = await conn.fetchval( + """SELECT EXISTS( + SELECT 1 FROM acls + WHERE resource_type = $1 + AND resource_id = $2 + AND grantee_type = 'user' + AND grantee_id = $3 + AND permission = 'full_control' + )""", + resource_type, resource_id, user_id + ) + + if has_full_control: + return True + + # Check for specific permission + has_permission = await conn.fetchval( + """SELECT EXISTS( + SELECT 1 FROM acls + WHERE resource_type = $1 + AND resource_id = $2 + AND grantee_type = 'user' + AND grantee_id = $3 + AND permission = $4 + )""", + resource_type, resource_id, user_id, required_permission.value + ) + + return has_permission + + async def _check_group_grants( + self, + conn, + user_id: str, + resource_type: str, + resource_id: int, + required_permission: Permission + ) -> bool: + """Check group-based grants.""" + # Get user's groups + user_groups = await conn.fetch( + "SELECT group_id FROM user_group_members WHERE user_id = $1", + user_id + ) + + if not user_groups: + return False + + group_ids = [g["group_id"] for g in user_groups] + + # Check for FULL_CONTROL in any group + has_full_control = await conn.fetchval( + """SELECT EXISTS( + SELECT 1 FROM acls + WHERE resource_type = $1 + AND resource_id = $2 + AND grantee_type = 'group' + AND grantee_id = ANY($3) + AND permission = 'full_control' + )""", + resource_type, resource_id, group_ids + ) + + if has_full_control: + return True + + # Check for specific permission + has_permission = await conn.fetchval( + """SELECT EXISTS( + SELECT 1 FROM acls + WHERE resource_type = $1 + AND resource_id = $2 + AND grantee_type = 'group' + AND grantee_id = ANY($3) + AND permission = $4 + )""", + resource_type, resource_id, group_ids, required_permission.value + ) + + return has_permission + + async def _check_bucket_policy( + self, + conn, + bucket_id: int, + required_permission: Permission + ) -> bool: + """Check bucket-wide policy for objects.""" + # Implementation would check bucket policy statements + # For now, return False + return False + + async def grant_access( + self, + grantee_type: GranteeType, + grantee_id: Optional[str], + resource_type: str, + resource_id: int, + permission: Permission + ) -> bool: + """Grant access to a resource.""" + async with self.db.acquire() as conn: + # Check if grantor has permission + # (This would be called with the requesting user's context) + + # Create grant + await conn.execute( + """INSERT INTO acls + (resource_type, resource_id, grantee_type, grantee_id, permission) + VALUES ($1, $2, $3, $4, $5) + ON CONFLICT (resource_type, resource_id, grantee_type, grantee_id, permission) + DO NOTHING""", + resource_type, resource_id, grantee_type.value, grantee_id, permission.value + ) + + logger.info( + f"Granted {permission.value} to {grantee_type.value}:{grantee_id} " + f"on {resource_type}:{resource_id}" + ) + + return True + + async def revoke_access( + self, + grantee_type: GranteeType, + grantee_id: Optional[str], + resource_type: str, + resource_id: int, + permission: Permission = None + ) -> bool: + """Revoke access to a resource.""" + async with self.db.acquire() as conn: + if permission: + result = await conn.execute( + """DELETE FROM acls + WHERE resource_type = $1 + AND resource_id = $2 + AND grantee_type = $3 + AND grantee_id = $4 + AND permission = $5""", + resource_type, resource_id, grantee_type.value, grantee_id, permission.value + ) + else: + # Revoke all permissions + result = await conn.execute( + """DELETE FROM acls + WHERE resource_type = $1 + AND resource_id = $2 + AND grantee_type = $3 + AND grantee_id = $4""", + resource_type, resource_id, grantee_type.value, grantee_id + ) + + deleted = int(result.split()[-1]) if result else 0 + logger.info(f"Revoked {deleted} grants from {grantee_type.value}:{grantee_id}") + return deleted > 0 + + async def get_acl( + self, + resource_type: str, + resource_id: int + ) -> List[Dict[str, Any]]: + """Get ACL for a resource.""" + async with self.db.acquire() as conn: + grants = await conn.fetch( + """SELECT * FROM acls + WHERE resource_type = $1 AND resource_id = $2 + ORDER BY grantee_type, grantee_id, permission""", + resource_type, resource_id + ) + + return [ + { + "grantee_type": g["grantee_type"], + "grantee_id": g["grantee_id"], + "permission": g["permission"] + } + for g in grants + ] + + async def set_acl( + self, + resource_type: str, + resource_id: int, + grants: List[Grant] + ) -> bool: + """Replace ACL for a resource.""" + async with self.db.acquire() as conn: + async with conn.transaction(): + # Delete existing ACLs + await conn.execute( + "DELETE FROM acls WHERE resource_type = $1 AND resource_id = $2", + resource_type, resource_id + ) + + # Insert new grants + for grant in grants: + await conn.execute( + """INSERT INTO acls + (resource_type, resource_id, grantee_type, grantee_id, permission) + VALUES ($1, $2, $3, $4, $5)""", + resource_type, resource_id, + grant.grantee_type.value, grant.grantee_id, grant.permission.value + ) + + logger.info(f"Set ACL for {resource_type}:{resource_id} with {len(grants)} grants") + return True + + async def make_public( + self, + resource_type: str, + resource_id: int, + read_only: bool = True + ) -> bool: + """Make a resource publicly accessible.""" + permission = Permission.READ if read_only else Permission.FULL_CONTROL + + return await self.grant_access( + grantee_type=GranteeType.ALL, + grantee_id=None, + resource_type=resource_type, + resource_id=resource_id, + permission=permission + ) + + async def make_private( + self, + resource_type: str, + resource_id: int + ) -> bool: + """Remove all public access.""" + return await self.revoke_access( + grantee_type=GranteeType.ALL, + grantee_id=None, + resource_type=resource_type, + resource_id=resource_id + ) +``` + +**Authentication middleware**: +```python +from fastapi import Request, HTTPException, Header +from typing import Optional + +class AuthContext: + """Authentication context for requests.""" + def __init__( + self, + user_id: Optional[str] = None, + access_key: Optional[str] = None, + is_authenticated: bool = False + ): + self.user_id = user_id + self.access_key = access_key + self.is_authenticated = is_authenticated + +async def get_auth_context( + request: Request, + authorization: Optional[str] = Header(None) +) -> AuthContext: + """ + Extract authentication context from request. + + Supports: + - AWS SigV4 style signatures (via Authorization header) + - Presigned URL access keys + """ + # Check presigned URL first + if "presigned" in request.query_params: + access_key = request.query_params["presigned"] + # Verify presigned URL + upload_service = get_upload_service() + presigned = await upload_service.verify_presigned_url(access_key, "get") + if presigned: + return AuthContext( + user_id=None, + access_key=access_key, + is_authenticated=True + ) + + # Check Authorization header + if authorization: + # Parse Authorization header (AWS SigV4 format) + # Authorization: AWS4-HMAC-SHA256 Credential=access_key/... + try: + parts = authorization.split(" ") + if len(parts) >= 2: + scheme, credentials = parts[0], parts[1] + + if scheme == "AWS4-HMAC-SHA256": + # Extract access key + for part in credentials.split(","): + if part.startswith("Credential="): + access_key = part.split("=")[1].split("/")[0] + + # Validate access key and get user + user_id = await _validate_access_key(access_key) + + return AuthContext( + user_id=user_id, + access_key=access_key, + is_authenticated=True + ) + except Exception as e: + logger.warning(f"Failed to parse Authorization header: {e}") + + # No valid authentication + return AuthContext() + +async def _validate_access_key(access_key: str) -> Optional[str]: + """Validate an access key and return user ID.""" + # In production, this would check against the database + # For now, mock implementation + return "user_123" + +def require_auth(permission: Permission = None): + """Decorator to require authentication for an endpoint.""" + async def dependency( + auth_context: AuthContext = Depends(get_auth_context) + ): + if not auth_context.is_authenticated: + raise HTTPException( + status_code=401, + detail="Authentication required" + ) + return auth_context + + return dependency +``` + +**Access control middleware**: +```python +class AccessControlMiddleware: + """Middleware for enforcing access control.""" + + def __init__(self, access_service: AccessControlService): + self.access_service = access_service + + async def require_permission( + self, + resource_type: str, + permission: Permission, + resource_id_param: str = "id" + ): + """Dependency factory to require specific permission.""" + async def check( + resource_id: int, + auth_context: AuthContext = Depends(get_auth_context) + ): + if not await self.access_service.check_permission( + user_id=auth_context.user_id, + resource_type=resource_type, + resource_id=resource_id, + required_permission=permission + ): + raise HTTPException( + status_code=403, + detail=f"Permission denied: {permission.value} required" + ) + + return {"resource_id": resource_id} + + return check + + async def require_bucket_permission( + self, + permission: Permission + ): + """Require bucket-level permission.""" + return await self.require_permission("bucket", permission, "bucket_id") + + async def require_object_permission( + self, + permission: Permission + ): + """Require object-level permission.""" + return await self.require_permission("object", permission, "object_id") +``` + +**ACL API endpoints**: +```python +from fastapi import APIRouter, Depends, HTTPException +from pydantic import BaseModel + +router = APIRouter(prefix="/v1/acl", tags=["acl"]) + +class GrantModel(BaseModel): + grantee_type: str # 'user', 'group', 'all' + grantee_id: Optional[str] = None + permission: str # 'read', 'write', 'delete', 'full_control' + +@router.get("/{resource_type}/{resource_id}") +async def get_acl( + resource_type: str, + resource_id: int, + auth_context: AuthContext = Depends(get_auth_context) +): + """Get ACL for a resource.""" + if not auth_context.is_authenticated: + raise HTTPException(status_code=401, detail="Authentication required") + + access_service = get_access_service() + + # Check if user can read ACL + if not await access_service.check_permission( + user_id=auth_context.user_id, + resource_type=resource_type, + resource_id=resource_id, + required_permission=Permission.READ_ACL + ): + raise HTTPException(status_code=403, detail="Cannot read ACL") + + grants = await access_service.get_acl(resource_type, resource_id) + return {"resource_type": resource_type, "resource_id": resource_id, "grants": grants} + +@router.put("/{resource_type}/{resource_id}") +async def set_acl( + resource_type: str, + resource_id: int, + grants: List[GrantModel], + auth_context: AuthContext = Depends(get_auth_context) +): + """Set ACL for a resource.""" + if not auth_context.is_authenticated: + raise HTTPException(status_code=401, detail="Authentication required") + + access_service = get_access_service() + + # Check if user can write ACL + if not await access_service.check_permission( + user_id=auth_context.user_id, + resource_type=resource_type, + resource_id=resource_id, + required_permission=Permission.WRITE_ACL + ): + raise HTTPException(status_code=403, detail="Cannot modify ACL") + + # Convert to Grant objects + grant_objects = [ + Grant( + grantee_type=GranteeType(g.grantee_type), + grantee_id=g.grantee_id, + permission=Permission(g.permission), + resource_type=resource_type, + resource_id=resource_id + ) + for g in grants + ] + + success = await access_service.set_acl(resource_type, resource_id, grant_objects) + + if not success: + raise HTTPException(status_code=500, detail="Failed to set ACL") + + return {"message": "ACL updated"} + +@router.post("/{resource_type}/{resource_id}/grants") +async def add_grant( + resource_type: str, + resource_id: int, + grant: GrantModel, + auth_context: AuthContext = Depends(get_auth_context) +): + """Add a grant to a resource.""" + if not auth_context.is_authenticated: + raise HTTPException(status_code=401, detail="Authentication required") + + access_service = get_access_service() + + if not await access_service.check_permission( + user_id=auth_context.user_id, + resource_type=resource_type, + resource_id=resource_id, + required_permission=Permission.WRITE_ACL + ): + raise HTTPException(status_code=403, detail="Cannot modify ACL") + + success = await access_service.grant_access( + grantee_type=GranteeType(grant.grantee_type), + grantee_id=grant.grantee_id, + resource_type=resource_type, + resource_id=resource_id, + permission=Permission(grant.permission) + ) + + if not success: + raise HTTPException(status_code=500, detail="Failed to add grant") + + return {"message": "Grant added"} + +@router.delete("/{resource_type}/{resource_id}/grants") +async def revoke_grant( + resource_type: str, + resource_id: int, + grantee_type: str, + grantee_id: Optional[str] = None, + permission: Optional[str] = None, + auth_context: AuthContext = Depends(get_auth_context) +): + """Revoke a grant from a resource.""" + if not auth_context.is_authenticated: + raise HTTPException(status_code=401, detail="Authentication required") + + access_service = get_access_service() + + if not await access_service.check_permission( + user_id=auth_context.user_id, + resource_type=resource_type, + resource_id=resource_id, + required_permission=Permission.WRITE_ACL + ): + raise HTTPException(status_code=403, detail="Cannot modify ACL") + + perm = Permission(permission) if permission else None + + success = await access_service.revoke_access( + grantee_type=GranteeType(grantee_type), + grantee_id=grantee_id, + resource_type=resource_type, + resource_id=resource_id, + permission=perm + ) + + if not success: + raise HTTPException(status_code=404, detail="Grant not found") + + return {"message": "Grant revoked"} + +@router.post("/{resource_type}/{resource_id}/public") +async def make_public( + resource_type: str, + resource_id: int, + read_only: bool = True, + auth_context: AuthContext = Depends(get_auth_context) +): + """Make a resource publicly accessible.""" + if not auth_context.is_authenticated: + raise HTTPException(status_code=401, detail="Authentication required") + + access_service = get_access_service() + + if not await access_service.check_permission( + user_id=auth_context.user_id, + resource_type=resource_type, + resource_id=resource_id, + required_permission=Permission.WRITE_ACL + ): + raise HTTPException(status_code=403, detail="Cannot modify ACL") + + success = await access_service.make_public(resource_type, resource_id, read_only) + + return {"message": f"Resource is now public (read_only={read_only})"} + +@router.delete("/{resource_type}/{resource_id}/public") +async def make_private( + resource_type: str, + resource_id: int, + auth_context: AuthContext = Depends(get_auth_context) +): + """Make a resource private.""" + if not auth_context.is_authenticated: + raise HTTPException(status_code=401, detail="Authentication required") + + access_service = get_access_service() + + if not await access_service.check_permission( + user_id=auth_context.user_id, + resource_type=resource_type, + resource_id=resource_id, + required_permission=Permission.WRITE_ACL + ): + raise HTTPException(status_code=403, detail="Cannot modify ACL") + + success = await access_service.make_private(resource_type, resource_id) + + return {"message": "Resource is now private"} +``` + +## Acceptance Criteria + +- [ ] Permissions are enforced correctly +- [ ] Public access works +- [ ] Owner has full control +- [ ] ACL can be read and modified +- [ ] Group membership grants work +- [ ] Presigned URLs bypass auth +- [ ] Unauthorized requests are rejected + +## Notes + +**Trade-offs**: +- ACL vs policy-based: ACL simpler for direct object access +- Deny vs allow-only: Allow-only simpler and less error-prone + +**Performance**: +- Cache permission checks in Redis +- Batch permission checks for list operations + +**Alternatives considered**: +- AWS IAM-style policies: More complex but more flexible +- OAuth2 scopes: Different model, harder to map diff --git a/ai_coder_1/subtasks/Decomp-005-06.md b/ai_coder_1/subtasks/Decomp-005-06.md new file mode 100644 index 0000000..79c3d71 --- /dev/null +++ b/ai_coder_1/subtasks/Decomp-005-06.md @@ -0,0 +1,594 @@ +# Subtask: File Download API + +**Parent Task**: Decomp/005 +**Subtask ID**: Decomp/005-06 +**Dependencies**: Decomp-005-01 (Storage Architecture), Decomp-005-05 (Access Control) + +## Description + +Implement file download API supporting range requests, direct-from-node streaming, presigned URLs, and download tracking. + +## Requirements + +- Download files from buckets +- Support HTTP range requests for partial content +- Stream directly from storage nodes +- Track download metrics +- Generate presigned download URLs +- Handle HEAD requests (metadata only) +- Support conditional downloads (ETag, If-Modified-Since) +- Response caching headers + +## Technical Specifications + +**Download service**: +```python +from typing import Optional, Dict, Any, Tuple +from dataclasses import dataclass +from datetime import datetime, timezone, timedelta +from pathlib import Path +import logging +import asyncio + +logger = logging.getLogger(__name__) + +@dataclass +class ObjectMetadata: + """Metadata about an object.""" + object_id: int + bucket_id: int + bucket_name: str + object_key: str + version_id: str + content_type: str + content_length: int + etag: str + last_modified: datetime + metadata: Dict[str, Any] + storage_nodes: List[str] + +@dataclass +class DownloadResult: + """Result of download preparation.""" + success: bool + metadata: ObjectMetadata = None + node_url: str = None + error: str = None + +class FileDownloadService: + """Service for handling file downloads.""" + + def __init__( + self, + db, + storage_adapter, + access_service, + hash_ring + ): + self.db = db + self.storage = storage_adapter + self.access = access_service + self.hash_ring = hash_ring + + async def get_object_metadata( + self, + bucket_id: int, + object_key: str, + version_id: str = None + ) -> Optional[ObjectMetadata]: + """Get object metadata.""" + async with self.db.acquire() as conn: + query = """ + SELECT o.*, b.name as bucket_name + FROM objects o + JOIN buckets b ON b.id = o.bucket_id + WHERE o.bucket_id = $1 AND o.object_key = $2 + """ + params = [bucket_id, object_key] + + if version_id: + query += " AND o.version_id = $3" + params.append(version_id) + else: + query += " AND o.is_latest = TRUE" + + obj = await conn.fetchrow(query, *params) + + if not obj: + return None + + return ObjectMetadata( + object_id=obj["id"], + bucket_id=obj["bucket_id"], + bucket_name=obj["bucket_name"], + object_key=obj["object_key"], + version_id=obj["version_id"], + content_type=obj.get("content_type", "application/octet-stream"), + content_length=obj["content_length"], + etag=obj["etag"], + last_modified=obj["modified_at"], + metadata=json.loads(obj.get("user_metadata", "{}")), + storage_nodes=json.loads(obj.get("storage_nodes", "[]")) + ) + + async def prepare_download( + self, + bucket_id: int, + object_key: str, + user_id: str = None, + version_id: str = None, + presigned_key: str = None + ) -> DownloadResult: + """ + Prepare a file for download. + + Returns metadata and the URL to download from (can redirect to storage node). + """ + # Check presigned URL access + if presigned_key: + valid = await self._verify_presigned_download(presigned_key) + if not valid: + return DownloadResult( + success=False, + error="Presigned URL invalid or expired" + ) + else: + # Check user permissions + if user_id: + # Check permission + has_access = await self.access.check_permission( + user_id=user_id, + resource_type="object", + resource_id=f"{bucket_id}:{object_key}", # Approximate + required_permission=Permission.READ + ) + if not has_access: + return DownloadResult( + success=False, + error="Access denied" + ) + else: + # Check for public access + obj = await self.get_object_metadata(bucket_id, object_key, version_id) + if not obj: + return DownloadResult(success=False, error="Object not found") + + is_public = await self._is_public(obj.object_id) + if not is_public: + return DownloadResult( + success=False, + error="Authentication required" + ) + + # Get object metadata + metadata = await self.get_object_metadata(bucket_id, object_key, version_id) + + if not metadata: + return DownloadResult(success=False, error="Object not found") + + # Select best storage node for download + # Prefer local node or fastest responding node + node_id = await self._select_download_node(metadata.storage_nodes) + + # Generate download URL + # In production, this would be the actual storage node URL + node_url = f"http://{node_id}:8080/files/{metadata.bucket_name}/{metadata.object_key}" + + # Update access time + async with self.db.acquire() as conn: + await conn.execute( + "UPDATE objects SET accessed_at = NOW() WHERE id = $1", + metadata.object_id + ) + + return DownloadResult( + success=True, + metadata=metadata, + node_url=node_url + ) + + async def read_file_data( + self, + bucket_id: int, + object_key: str, + range_header: str = None + ) -> Tuple[Optional[ObjectMetadata], Optional[bytes], Dict[str, str]]: + """ + Read file data directly (for streaming response). + + Returns (metadata, data, headers). + """ + metadata = await self.get_object_metadata(bucket_id, object_key) + + if not metadata: + return None, None, {} + + # Parse range header + content_range = None + status_code = 200 + + if range_header: + start, end = self._parse_range_header(range_header, metadata.content_length) + if start is not None: + # Read partial content + node_id = await self._select_download_node(metadata.storage_nodes) + file_path = f"{metadata.bucket_name}/{metadata.object_key}" + + all_data = await self.storage.read_file(node_id, file_path) + data = all_data[start:end+1] + + headers = { + "Content-Type": metadata.content_type, + "Content-Length": str(len(data)), + "Content-Range": f"bytes {start}-{end}/{metadata.content_length}", + "ETag": metadata.etag, + "Last-Modified": metadata.last_modified.strftime("%a, %d %b %Y %H:%M:%S GMT") + } + status_code = 206 + return metadata, data, headers + + # Read full file + node_id = await self._select_download_node(metadata.storage_nodes) + file_path = f"{metadata.bucket_name}/{metadata.object_key}" + data = await self.storage.read_file(node_id, file_path) + + headers = { + "Content-Type": metadata.content_type, + "Content-Length": str(metadata.content_length), + "Content-Disposition": f'inline; filename="{Path(metadata.object_key).name}"', + "ETag": metadata.etag, + "Last-Modified": metadata.last_modified.strftime("%a, %d %b %Y %H:%M:%S GMT"), + "Cache-Control": "private, max-age=3600", + "Accept-Ranges": "bytes" + } + + return metadata, data, headers + + async def create_presigned_download_url( + self, + bucket_id: int, + object_key: str, + expires_in_seconds: int = 3600, + version_id: str = None + ) -> str: + """Create a presigned URL for download.""" + # Verify object exists and get ID + metadata = await self.get_object_metadata(bucket_id, object_key, version_id) + + if not metadata: + raise ValueError("Object not found") + + # Generate presigned key + import uuid + access_key = f"presigned:{uuid.uuid4().hex}" + expires_at = datetime.now(timezone.utc) + timedelta(seconds=expires_in_seconds) + + async with self.db.acquire() as conn: + await conn.execute( + """INSERT INTO presigned_urls + (object_id, access_key, expires_at, operation) + VALUES ($1, $2, $3, 'get')""", + metadata.object_id, access_key, expires_at + ) + + return f"https://storage.example.com/v1/download/{access_key}" + + async def _verify_presigned_download(self, access_key: str) -> bool: + """Verify a presigned download URL.""" + async with self.db.acquire() as conn: + record = await conn.fetchrow( + """SELECT pu.* + FROM presigned_urls pu + WHERE pu.access_key = $1 + AND pu.operation = 'get' + AND pu.expires_at > NOW()""", + access_key + ) + + return record is not None + + async def _is_public(self, object_id: int) -> bool: + """Check if object is publicly accessible.""" + async with self.db.acquire() as conn: + return await conn.fetchval( + """SELECT EXISTS( + SELECT 1 FROM acls + WHERE resource_type = 'object' + AND resource_id = $1 + AND grantee_type = 'all' + AND permission = 'read' + )""", + object_id + ) + + async def _select_download_node(self, node_ids: List[str]) -> str: + """Select the best node for download.""" + if not node_ids: + raise ValueError("No storage nodes available") + + # Simple round-robin or random selection + # In production, would consider: + # - Node proximity/location + # - Current load + # - Health status + # - Network latency + + import random + return random.choice(node_ids) + + def _parse_range_header( + self, + range_header: str, + content_length: int + ) -> Tuple[Optional[int], Optional[int]]: + """ + Parse HTTP Range header. + + Returns (start, end) tuple or (None, None) if invalid. + Supports format: "bytes=start-end" + """ + if not range_header.startswith("bytes="): + return None, None + + try: + range_spec = range_header[6:] # Remove "bytes=" + + if "-" not in range_spec: + return None, None + + start_str, end_str = range_spec.split("-", 1) + + start = int(start_str) if start_str else 0 + + if end_str: + end = int(end_str) + else: + end = content_length - 1 + + # Validate range + if start < 0 or end >= content_length or start > end: + return None, None + + return start, end + + except (ValueError, IndexError): + return None, None + + async def log_download( + self, + bucket_id: int, + object_id: int, + user_id: str = None, + bytes_sent: int = None, + http_status: int = None + ): + """Log download to audit table.""" + async with self.db.acquire() as conn: + await conn.execute( + """INSERT INTO audit_log + (bucket_id, object_id, operation, user_id, bytes_sent, http_status) + VALUES ($1, $2, 'GET', $3, $4, $5)""", + bucket_id, object_id, user_id, bytes_sent, http_status + ) +``` + +**Download API endpoints**: +```python +from fastapi import APIRouter, Response, Request, HTTPException, Header, Query +from fastapi.responses import StreamingResponse, RedirectResponse +from typing import Optional + +router = APIRouter(prefix="/v1", tags=["download"]) + +@router.head("/buckets/{bucket_id}/objects/{object_key:path}") +async def head_object( + bucket_id: int, + object_key: str, + version_id: Optional[str] = None, + if_match: Optional[str] = Header(None), # ETag match + if_none_match: Optional[str] = Header(None), # ETag none match + auth_context: AuthContext = Depends(get_auth_context) +): + """Get object metadata without downloading.""" + download_service = get_download_service() + + result = await download_service.prepare_download( + bucket_id=bucket_id, + object_key=object_key, + user_id=auth_context.user_id, + version_id=version_id + ) + + if not result.success: + if result.error == "Access denied": + raise HTTPException(status_code=403, detail=result.error) + raise HTTPException(status_code=404, detail=result.error) + + metadata = result.metadata + + # Check conditional requests + if if_none_match and if_none_match == metadata.etag: + return Response(status_code=304) + + if if_match and if_match != metadata.etag: + raise HTTPException(status_code=412, detail="Precondition Failed") + + return Response( + content_type=metadata.content_type, + headers={ + "Content-Length": str(metadata.content_length), + "ETag": metadata.etag, + "Last-Modified": metadata.last_modified.strftime("%a, %d %b %Y %H:%M:%S GMT"), + "Cache-Control": "private, max-age=3600", + "Accept-Ranges": "bytes" + } + ) + +@router.get("/buckets/{bucket_id}/objects/{object_key:path}") +async def download_object( + bucket_id: int, + object_key: str, + version_id: Optional[str] = None, + range: Optional[str] = Header(None), + if_match: Optional[str] = Header(None), + if_none_match: Optional[str] = Header(None), + auth_context: AuthContext = Depends(get_auth_context) +): + """Download an object.""" + download_service = get_download_service() + + # Check conditional requests first + metadata = await download_service.get_object_metadata(bucket_id, object_key, version_id) + + if not metadata: + raise HTTPException(status_code=404, detail="Object not found") + + if if_none_match and if_none_match == metadata.etag: + return Response(status_code=304) + + if if_match and if_match != metadata.etag: + raise HTTPException(status_code=412, detail="Precondition Failed") + + # Prepare download + result = await download_service.prepare_download( + bucket_id=bucket_id, + object_key=object_key, + user_id=auth_context.user_id, + version_id=version_id + ) + + if not result.success: + if result.error == "Access denied": + raise HTTPException(status_code=403, detail=result.error) + raise HTTPException(status_code=404, detail=result.error) + + # Get file data + obj_metadata, data, headers = await download_service.read_file_data( + bucket_id=bucket_id, + object_key=object_key, + range_header=range + ) + + if not obj_metadata: + raise HTTPException(status_code=404, detail="Object not found") + + # Determine status code + status_code = 206 if range and "Content-Range" in headers else 200 + + # Log download + await download_service.log_download( + bucket_id=bucket_id, + object_id=obj_metadata.object_id, + user_id=auth_context.user_id, + bytes_sent=len(data), + http_status=status_code + ) + + return Response( + content=data, + status_code=status_code, + media_type=obj_metadata.content_type, + headers=headers + ) + +@router.get("/download/{access_key}") +async def download_via_presigned_url( + access_key: str, + range: Optional[str] = Header(None) +): + """Download via presigned URL (no auth required).""" + download_service = get_download_service() + + # Verify presigned URL and get object info + async with download_service.db.acquire() as conn: + presigned = await conn.fetchrow( + """SELECT pu.*, o.bucket_id, o.object_key, o.id as object_id + FROM presigned_urls pu + JOIN objects o ON o.id = pu.object_id + WHERE pu.access_key = $1 + AND pu.operation = 'get' + AND pu.expires_at > NOW()""", + access_key + ) + + if not presigned: + raise HTTPException(status_code=403, detail="Invalid or expired presigned URL") + + # Get file data + obj_metadata, data, headers = await download_service.read_file_data( + bucket_id=presigned["bucket_id"], + object_key=presigned["object_key"], + range_header=range + ) + + if not obj_metadata: + raise HTTPException(status_code=404, detail="Object not found") + + status_code = 206 if range and "Content-Range" in headers else 200 + + return Response( + content=data, + status_code=status_code, + media_type=obj_metadata.content_type, + headers=headers + ) + +@router.post("/buckets/{bucket_id}/objects/{object_key:path}/presign") +async def create_presigned_download( + bucket_id: int, + object_key: str, + expires_in: int = Query(3600, description="URL expiration in seconds", ge=60, le=86400), + version_id: Optional[str] = None, + auth_context: AuthContext = Depends(get_auth_context) +): + """Create a presigned download URL.""" + download_service = get_download_service() + + # Verify permissions + has_access = await download_service.access.check_permission( + user_id=auth_context.user_id, + resource_type="object", + resource_id=f"{bucket_id}:{object_key}", + required_permission=Permission.READ + ) + + if not has_access: + raise HTTPException(status_code=403, detail="Access denied") + + try: + url = await download_service.create_presigned_download_url( + bucket_id=bucket_id, + object_key=object_key, + expires_in_seconds=expires_in, + version_id=version_id + ) + + return {"download_url": url, "expires_in": expires_in} + except ValueError as e: + raise HTTPException(status_code=404, detail=str(e)) +``` + +## Acceptance Criteria + +- [ ] Files can be downloaded by authorized users +- [ ] Range requests work correctly +- [ ] HEAD requests return metadata only +- [ ] Conditional requests (ETag) work +- [ ] Presigned URLs work without auth +- [ ] Downloads are logged +- [ ] Public files are accessible + +## Notes + +**Trade-offs**: +- Redirect vs proxy: Redirect to storage node for performance +- Synchronous vs streaming: Streaming for memory efficiency + +**Performance**: +- Use CDN caching for public objects +- Implement byte-range seek for large files +- Cache metadata in Redis + +**Alternatives considered**: +- CloudFront/S3 direct: Simpler but less control +- Nginx X-Accel-Redirect: Faster for large files diff --git a/ai_coder_1/subtasks/Decomp-005-07.md b/ai_coder_1/subtasks/Decomp-005-07.md new file mode 100644 index 0000000..1dd9938 --- /dev/null +++ b/ai_coder_1/subtasks/Decomp-005-07.md @@ -0,0 +1,637 @@ +# Subtask: File Versioning + +**Parent Task**: Decomp/005 +**Subtask ID**: Decomp/005-07 +**Dependencies**: Decomp-005-01 (Storage Architecture), Decomp-005-02 (File Upload API) + +## Description + +Implement file versioning system allowing multiple versions of the same object. Support version listing, retrieving specific versions, restoring previous versions, and version deletion. + +## Requirements + +- Enable/disable versioning per bucket +- Create new versions on overwrite +- List all versions of an object +- Retrieve specific version +- Delete specific version +- Restore previous version +- Track version history +- Count versions against bucket quota + +## Technical Specifications + +**Versioning service**: +```python +from typing import List, Dict, Any, Optional +from dataclasses import dataclass +from datetime import datetime, timezone +import logging +import uuid + +logger = logging.getLogger(__name__) + +@dataclass +class ObjectVersion: + """Information about an object version.""" + version_id: str + object_id: int + is_latest: bool + content_length: int + etag: str + last_modified: datetime + is_delete_marker: bool = False + +@dataclass +class VersionListResult: + """Result of listing versions.""" + object_key: str + versions: List[ObjectVersion] + is_truncated: bool + next_marker: str = None + +class VersioningService: + """Service for managing object versioning.""" + + def __init__(self, db): + self.db = db + + async def enable_versioning(self, bucket_id: int) -> bool: + """Enable versioning for a bucket.""" + async with self.db.acquire() as conn: + # Check if bucket exists + bucket = await conn.fetchrow( + "SELECT * FROM buckets WHERE id = $1", + bucket_id + ) + + if not bucket: + raise ValueError("Bucket not found") + + if bucket["versioning_enabled"]: + return True # Already enabled + + # Enable versioning + await conn.execute( + "UPDATE buckets SET versioning_enabled = TRUE WHERE id = $1", + bucket_id + ) + + logger.info(f"Enabled versioning for bucket {bucket_id}") + return True + + async def disable_versioning(self, bucket_id: int) -> bool: + """ + Disable versioning for a bucket. + + WARNING: This only affects new overwrites. Existing versions are kept. + To clean up old versions, use cleanup_old_versions(). + """ + async with self.db.acquire() as conn: + await conn.execute( + "UPDATE buckets SET versioning_enabled = FALSE WHERE id = $1", + bucket_id + ) + + logger.info(f"Disabled versioning for bucket {bucket_id}") + return True + + async def is_versioning_enabled(self, bucket_id: int) -> bool: + """Check if versioning is enabled for a bucket.""" + async with self.db.acquire() as conn: + return await conn.fetchval( + "SELECT versioning_enabled FROM buckets WHERE id = $1", + bucket_id + ) + + async def list_object_versions( + self, + bucket_id: int, + object_key: str, + limit: int = 100, + marker: str = None + ) -> VersionListResult: + """List all versions of an object.""" + async with self.db.acquire() as conn: + query = """ + SELECT o.id, o.version_id, o.is_latest, o.object_key, + o.content_length, o.etag, o.modified_at as last_modified, + o.is_delete_marker + FROM objects o + WHERE o.bucket_id = $1 AND o.object_key = $2 + """ + params = [bucket_id, object_key] + + if marker: + query += " AND o.version_id > $3" + params.append(marker) + + query += " ORDER BY o.modified_at DESC" + query += f" LIMIT {limit + 1}" # Fetch one extra to check truncation + + rows = await conn.fetch(query, *params) + + is_truncated = len(rows) > limit + if is_truncated: + rows = rows[:limit] + next_marker = rows[-1]["version_id"] + else: + next_marker = None + + versions = [ + ObjectVersion( + version_id=r["version_id"], + object_id=r["id"], + is_latest=r["is_latest"], + content_length=r["content_length"], + etag=r["etag"], + last_modified=r["last_modified"], + is_delete_marker=r["is_delete_marker"] + ) + for r in rows + ] + + return VersionListResult( + object_key=object_key, + versions=versions, + is_truncated=is_truncated, + next_marker=next_marker + ) + + async def get_version( + self, + bucket_id: int, + object_key: str, + version_id: str + ) -> Optional[Dict[str, Any]]: + """Get a specific version of an object.""" + async with self.db.acquire() as conn: + obj = await conn.fetchrow( + """SELECT o.*, b.name as bucket_name + FROM objects o + JOIN buckets b ON b.id = o.bucket_id + WHERE o.bucket_id = $1 + AND o.object_key = $2 + AND o.version_id = $3""", + bucket_id, object_key, version_id + ) + + if not obj: + return None + + return { + "version_id": obj["version_id"], + "object_id": obj["id"], + "object_key": obj["object_key"], + "bucket_id": obj["bucket_id"], + "bucket_name": obj["bucket_name"], + "content_type": obj.get("content_type"), + "content_length": obj["content_length"], + "etag": obj["etag"], + "last_modified": obj["modified_at"], + "is_latest": obj["is_latest"], + "is_delete_marker": obj["is_delete_marker"], + "metadata": json.loads(obj.get("user_metadata", "{}")), + "storage_nodes": json.loads(obj.get("storage_nodes", "[]")) + } + + async def restore_version( + self, + bucket_id: int, + object_key: str, + version_id: str + ) -> bool: + """ + Restore a previous version as the latest version. + + Creates a new version with the content from the specified version. + """ + async with self.db.acquire() as conn: + async with conn.transaction(): + # Get the version to restore + old_version = await conn.fetchrow( + """SELECT * FROM objects + WHERE bucket_id = $1 + AND object_key = $2 + AND version_id = $3""", + bucket_id, object_key, version_id + ) + + if not old_version: + raise ValueError("Version not found") + + # Check if versioning is enabled + bucket = await conn.fetchrow( + "SELECT versioning_enabled FROM buckets WHERE id = $1", + bucket_id + ) + + if not bucket or not bucket["versioning_enabled"]: + raise ValueError("Versioning not enabled for this bucket") + + # Mark current latest as not latest + await conn.execute( + """UPDATE objects + SET is_latest = FALSE + WHERE bucket_id = $1 + AND object_key = $2 + AND is_latest = TRUE""", + bucket_id, object_key + ) + + # Create a new version based on the old version + # This copies the storage reference (files are deduplicated) + new_version_id = f"v-{uuid.uuid4().hex}" + + await conn.execute( + """INSERT INTO objects + (bucket_id, object_key, version_id, is_latest, + content_type, content_length, etag, checksum_sha256, + storage_class, storage_nodes, user_metadata, + modified_at) + SELECT bucket_id, object_key, $1, TRUE, + content_type, content_length, etag, checksum_sha256, + storage_class, storage_nodes, user_metadata, + NOW() + FROM objects + WHERE id = $2""", + new_version_id, + old_version["id"] + ) + + logger.info( + f"Restored version {version_id} as {new_version_id} " + f"for {object_key}" + ) + + return True + + async def delete_version( + self, + bucket_id: int, + object_key: str, + version_id: str + ) -> bool: + """ + Delete a specific version of an object. + + Cannot delete the latest version. Use delete_object() instead. + """ + async with self.db.acquire() as conn: + # Check if this is the latest version + is_latest = await conn.fetchval( + """SELECT is_latest FROM objects + WHERE bucket_id = $1 + AND object_key = $2 + AND version_id = $3""", + bucket_id, object_key, version_id + ) + + if is_latest: + raise ValueError( + "Cannot delete latest version directly. " + "Use delete_object() to delete the current version." + ) + + # Delete the version + result = await conn.execute( + """DELETE FROM objects + WHERE bucket_id = $1 + AND object_key = $2 + AND version_id = $3""", + bucket_id, object_key, version_id + ) + + deleted = int(result.split()[-1]) if result else 0 + + if deleted > 0: + logger.info(f"Deleted version {version_id} of {object_key}") + return True + + return False + + async def create_delete_marker( + self, + bucket_id: int, + object_key: str + ) -> str: + """ + Create a delete marker for versioned object. + + This "deletes" the object while preserving all versions. + """ + # Check if versioning is enabled + if not await self.is_versioning_enabled(bucket_id): + # Just delete the object normally + await self.delete_object(bucket_id, object_key) + return None + + async with self.db.acquire() as conn: + async with conn.transaction(): + # Mark all current versions as not latest + await conn.execute( + """UPDATE objects + SET is_latest = FALSE + WHERE bucket_id = $1 + AND object_key = $2 + AND is_latest = TRUE""", + bucket_id, object_key + ) + + # Create delete marker + version_id = f"v-delete-{uuid.uuid4().hex}" + + await conn.execute( + """INSERT INTO objects + (bucket_id, object_key, version_id, is_latest, is_delete_marker, + content_length, etag, modified_at) + VALUES ($1, $2, $3, TRUE, TRUE, 0, '', NOW())""", + bucket_id, object_key, version_id + ) + + logger.info(f"Created delete marker for {object_key}") + return version_id + + async def delete_object( + self, + bucket_id: int, + object_key: str + ) -> bool: + """ + Permanently delete an object and all its versions. + + WARNING: This cannot be undone! + """ + async with self.db.acquire() as conn: + # Get all versions to clean up files + versions = await conn.fetch( + """SELECT id, storage_nodes FROM objects + WHERE bucket_id = $1 AND object_key = $2""", + bucket_id, object_key + ) + + # Delete all versions (cascades to dependent records) + result = await conn.execute( + "DELETE FROM objects WHERE bucket_id = $1 AND object_key = $2", + bucket_id, object_key + ) + + deleted = int(result.split()[-1]) if result else 0 + + if deleted > 0: + logger.info(f"Deleted {deleted} versions of {object_key}") + + # Note: Actual file cleanup would be handled by a separate garbage collection process + + return deleted > 0 + + async def cleanup_old_versions( + self, + bucket_id: int, + keep_versions: int = 10, + older_than_days: int = 30 + ) -> int: + """ + Clean up old non-current versions. + + Keeps at most keep_versions per object, and versions newer than older_than_days. + """ + async with self.db.acquire() as conn: + # Find objects with too many versions + objects = await conn.fetch( + """SELECT object_key + FROM objects + WHERE bucket_id = $1 + AND is_delete_marker = FALSE + AND is_latest = FALSE + AND modified_at < NOW() - INTERVAL '1 day' * $2 + GROUP BY object_key + HAVING COUNT(*) > $3 + LIMIT 1000""", + bucket_id, older_than_days, keep_versions + ) + + deleted = 0 + + for obj in objects: + object_key = obj["object_key"] + + # Get versions to keep (most recent + is_latest) + keep = await conn.fetch( + """SELECT version_id + FROM objects + WHERE bucket_id = $1 + AND object_key = $2 + AND (is_latest = TRUE OR is_delete_marker = FALSE) + ORDER BY modified_at DESC + LIMIT $3""", + bucket_id, object_key, keep_versions + ) + + keep_ids = [v["version_id"] for v in keep] + + # Delete old versions + result = await conn.execute( + """DELETE FROM objects + WHERE bucket_id = $1 + AND object_key = $2 + AND is_latest = FALSE + AND is_delete_marker = FALSE + AND version_id != ALL($3) + AND modified_at < NOW() - INTERVAL '1 day' * $4""", + bucket_id, object_key, keep_ids, older_than_days + ) + + count = int(result.split()[-1]) if result else 0 + deleted += count + + if deleted > 0: + logger.info(f"Cleaned up {deleted} old versions in bucket {bucket_id}") + + return deleted + + async def get_version_count(self, bucket_id: int) -> int: + """Get total number of versions in a bucket.""" + async with self.db.acquire() as conn: + return await conn.fetchval( + "SELECT COUNT(*) FROM objects WHERE bucket_id = $1", + bucket_id + ) + + async def get_version_stats(self, bucket_id: int) -> Dict[str, Any]: + """Get versioning statistics for a bucket.""" + async with self.db.acquire() as conn: + stats = await conn.fetchrow( + """SELECT + COUNT(*) FILTER (is_latest = TRUE) as current_objects, + COUNT(*) FILTER (is_latest = FALSE) as old_versions, + COUNT(*) FILTER (is_delete_marker = TRUE) as delete_markers, + SUM(content_length) FILTER (is_latest = TRUE) as current_bytes, + SUM(content_length) FILTER (is_latest = FALSE) as version_bytes, + COUNT(DISTINCT object_key) as unique_keys + FROM objects + WHERE bucket_id = $1""", + bucket_id + ) + + return { + "current_objects": stats["current_objects"] or 0, + "old_versions": stats["old_versions"] or 0, + "delete_markers": stats["delete_markers"] or 0, + "total_versions": (stats["current_objects"] or 0) + (stats["old_versions"] or 0), + "current_bytes": int(stats["current_bytes"] or 0), + "version_bytes": int(stats["version_bytes"] or 0), + "total_bytes": int((stats["current_bytes"] or 0) + (stats["version_bytes"] or 0)), + "unique_keys": stats["unique_keys"] or 0 + } +``` + +**Versioning API endpoints**: +```python +from fastapi import APIRouter, HTTPException, Query +from typing import Optional + +router = APIRouter(prefix="/v1/versioning", tags=["versioning"]) + +@router.put("/buckets/{bucket_id}/versioning") +async def enable_bucket_versioning(bucket_id: int): + """Enable versioning for a bucket.""" + service = get_versioning_service() + + try: + success = await service.enable_versioning(bucket_id) + return {"message": "Versioning enabled", "bucket_id": bucket_id} + except ValueError as e: + raise HTTPException(status_code=400, detail=str(e)) + +@router.delete("/buckets/{bucket_id}/versioning") +async def disable_bucket_versioning(bucket_id: int): + """Disable versioning for a bucket.""" + service = get_versioning_service() + + success = await service.disable_versioning(bucket_id) + return {"message": "Versioning disabled", "bucket_id": bucket_id} + +@router.get("/buckets/{bucket_id}/objects/{object_key:path}/versions") +async def list_object_versions( + bucket_id: int, + object_key: str, + limit: int = Query(100, ge=1, le=1000), + marker: str = None +): + """List all versions of an object.""" + service = get_versioning_service() + + result = await service.list_object_versions( + bucket_id=bucket_id, + object_key=object_key, + limit=limit, + marker=marker + ) + + return { + "object_key": result.object_key, + "versions": [ + { + "version_id": v.version_id, + "is_latest": v.is_latest, + "size": v.content_length, + "etag": v.etag, + "last_modified": v.last_modified.isoformat(), + "is_delete_marker": v.is_delete_marker + } + for v in result.versions + ], + "is_truncated": result.is_truncated, + "next_marker": result.next_marker + } + +@router.get("/buckets/{bucket_id}/objects/{object_key:path}/versions/{version_id}") +async def get_object_version( + bucket_id: int, + object_key: str, + version_id: str +): + """Get a specific version of an object.""" + service = get_versioning_service() + + version = await service.get_version(bucket_id, object_key, version_id) + + if not version: + raise HTTPException(status_code=404, detail="Version not found") + + return { + "version_id": version["version_id"], + "object_key": version["object_key"], + "content_type": version["content_type"], + "size": version["content_length"], + "etag": version["etag"], + "last_modified": version["last_modified"].isoformat(), + "is_latest": version["is_latest"], + "metadata": version["metadata"] + } + +@router.post("/buckets/{bucket_id}/objects/{object_key:path}/versions/{version_id}/restore") +async def restore_object_version( + bucket_id: int, + object_key: str, + version_id: str +): + """Restore a previous version as the current version.""" + service = get_versioning_service() + + try: + success = await service.restore_version(bucket_id, object_key, version_id) + return {"message": "Version restored"} + except ValueError as e: + raise HTTPException(status_code=400, detail=str(e)) + +@router.delete("/buckets/{bucket_id}/objects/{object_key:path}/versions/{version_id}") +async def delete_object_version( + bucket_id: int, + object_key: str, + version_id: str +): + """Delete a specific version (not the current version).""" + service = get_versioning_service() + + try: + success = await service.delete_version(bucket_id, object_key, version_id) + if not success: + raise HTTPException(status_code=404, detail="Version not found") + return {"message": "Version deleted"} + except ValueError as e: + raise HTTPException(status_code=400, detail=str(e)) + +@router.get("/buckets/{bucket_id}/stats") +async def get_bucket_version_stats(bucket_id: int): + """Get versioning statistics for a bucket.""" + service = get_versioning_service() + + stats = await service.get_version_stats(bucket_id) + return stats +``` + +## Acceptance Criteria + +- [ ] Versioning can be enabled/disabled per bucket +- [ ] Overwrites create new versions +- [ ] All versions can be listed +- [ ] Specific versions can be retrieved +- [ ] Old versions can be restored +- [ ] Non-latest versions can be deleted +- [ ] Delete markers work correctly + +## Notes + +**Trade-offs**: +- Hard delete vs soft delete: Soft delete markers for recovery +- Version limits: Unlimited with manual cleanup + +**Performance**: +- Index on (bucket_id, object_key, version_id) +- Separate index for is_latest + +**Alternatives considered**: +- Git-style versioning: Overkill for object storage +- Deduplication by content: Storage efficiency vs complexity diff --git a/ai_coder_1/subtasks/Decomp-005-08.md b/ai_coder_1/subtasks/Decomp-005-08.md new file mode 100644 index 0000000..9796029 --- /dev/null +++ b/ai_coder_1/subtasks/Decomp-005-08.md @@ -0,0 +1,694 @@ +# Subtask: Lifecycle Management + +**Parent Task**: Decomp/005 +**Subtask ID**: Decomp/005-08 +**Dependencies**: Decomp-005-01 (Storage Architecture) + +## Description + +Implement lifecycle management for objects. Support automatic transitions between storage classes, expiration rules, and archival/deletion policies. + +## Requirements + +- Define lifecycle rules per bucket +- Auto-transition objects to cheaper storage +- Expire/delete old objects +- Support prefix-based rules +- Track lifecycle status +- Apply rules asynchronously +- Abort in-progress lifecycle operations + +## Technical Specifications + +**Lifecycle rule definitions**: +```python +from typing import List, Dict, Any, Optional +from dataclasses import dataclass +from datetime import datetime, timezone, timedelta +from enum import Enum +import logging + +logger = logging.getLogger(__name__) + +class StorageClass(Enum): + """Storage class tiers.""" + STANDARD = "standard" + INFREQUENT_ACCESS = "infrequent" + ARCHIVE = "archive" + DEEP_ARCHIVE = "deep_archive" + +class LifecycleAction(Enum): + """Types of lifecycle actions.""" + TRANSITION = "transition" + EXPIRE = "expire" + +@dataclass +class TransitionRule: + """Rule for transitioning objects to a different storage class.""" + days: int + target_storage_class: StorageClass + prefix: Optional[str] = None + +@dataclass +class ExpirationRule: + """Rule for expiring/deleting objects.""" + days: int + prefix: Optional[str] = None + expired_object_delete_marker: bool = True + +@dataclass +class LifecyclePolicy: + """A lifecycle policy for a bucket.""" + id: Optional[int] + bucket_id: int + name: str + transitions: List[TransitionRule] + expirations: List[ExpirationRule] + is_enabled: bool = True + created_at: datetime = None + updated_at: datetime = None + +class LifecycleManager: + """Service for managing object lifecycle policies.""" + + def __init__(self, db, storage_service): + self.db = db + self.storage = storage_service + + async def create_policy( + self, + bucket_id: int, + name: str, + transitions: List[Dict[str, Any]] = None, + expirations: List[Dict[str, Any]] = None + ) -> int: + """ + Create a lifecycle policy for a bucket. + + Args: + bucket_id: Bucket ID + name: Policy name + transitions: List of transition rules + [{days: int, storage_class: str, prefix: str}] + expirations: List of expiration rules + [{days: int, prefix: str}] + + Returns: + Policy ID + """ + # Convert dicts to rule objects + transition_rules = [] + if transitions: + for t in transitions: + transition_rules.append(TransitionRule( + days=t["days"], + target_storage_class=StorageClass(t["storage_class"]), + prefix=t.get("prefix") + )) + + expiration_rules = [] + if expirations: + for e in expirations: + expiration_rules.append(ExpirationRule( + days=e["days"], + prefix=e.get("prefix") + )) + + async with self.db.acquire() as conn: + policy_id = await conn.fetchval( + """INSERT INTO lifecycle_policies + (bucket_id, name, rules, is_enabled) + VALUES ($1, $2, $3, TRUE) + RETURNING id""", + bucket_id, + name, + json.dumps({ + "transitions": [ + { + "days": t.days, + "storage_class": t.target_storage_class.value, + "prefix": t.prefix + } + for t in transition_rules + ], + "expirations": [ + { + "days": e.days, + "prefix": e.prefix + } + for e in expiration_rules + ] + }) + ) + + logger.info(f"Created lifecycle policy {policy_id} for bucket {bucket_id}") + return policy_id + + async def update_policy( + self, + policy_id: int, + name: str = None, + transitions: List[Dict[str, Any]] = None, + expirations: List[Dict[str, Any]] = None, + is_enabled: bool = None + ) -> bool: + """Update an existing lifecycle policy.""" + updates = [] + params = [] + + if name is not None: + updates.append("name = $2") + params.append(name) + + if is_enabled is not None: + updates.append("is_enabled = $2") + params.append(is_enabled) + + if transitions is not None or expirations is not None: + # Rebuild rules + current_rules = await self.get_policy(policy_id) + if current_rules: + final_transitions = transitions if transitions is not None else current_rules.transitions + final_expirations = expirations if expirations is not None else current_rules.expirations + else: + final_transitions = transitions or [] + final_expirations = expirations or [] + + updates.append("rules = $2") + params.append(json.dumps({ + "transitions": final_transitions, + "expirations": final_expirations + })) + + if updates: + params.append(policy_id) + query = f"UPDATE lifecycle_policies SET {', '.join(updates)} WHERE id = ${len(params)}" + + async with self.db.acquire() as conn: + await conn.execute(query, *params) + await conn.execute( + "UPDATE lifecycle_policies SET updated_at = NOW() WHERE id = $1", + policy_id + ) + + return True + + async def delete_policy(self, policy_id: int) -> bool: + """Delete a lifecycle policy.""" + async with self.db.acquire() as conn: + result = await conn.execute( + "DELETE FROM lifecycle_policies WHERE id = $1", + policy_id + ) + return result != "DELETE 0" + + async def get_policy(self, policy_id: int) -> Optional[LifecyclePolicy]: + """Get a lifecycle policy by ID.""" + async with self.db.acquire() as conn: + policy = await conn.fetchrow( + """SELECT * FROM lifecycle_policies WHERE id = $1""", + policy_id + ) + + if not policy: + return None + + rules = json.loads(policy["rules"]) + + return LifecyclePolicy( + id=policy["id"], + bucket_id=policy["bucket_id"], + name=policy["name"], + transitions=[ + TransitionRule( + days=r["days"], + target_storage_class=StorageClass(r["storage_class"]), + prefix=r.get("prefix") + ) + for r in rules.get("transitions", []) + ], + expirations=[ + ExpirationRule( + days=e["days"], + prefix=e.get("prefix") + ) + for e in rules.get("expirations", []) + ], + is_enabled=policy["is_enabled"], + created_at=policy["created_at"], + updated_at=policy["updated_at"] + ) + + async def list_policies(self, bucket_id: int) -> List[LifecyclePolicy]: + """List all lifecycle policies for a bucket.""" + async with self.db.acquire() as conn: + policies = await conn.fetch( + """SELECT * FROM lifecycle_policies + WHERE bucket_id = $1 + ORDER BY created_at DESC""", + bucket_id + ) + + result = [] + for policy in policies: + rules = json.loads(policy["rules"]) + result.append( + LifecyclePolicy( + id=policy["id"], + bucket_id=policy["bucket_id"], + name=policy["name"], + transitions=[ + TransitionRule( + days=r["days"], + target_storage_class=StorageClass(r["storage_class"]), + prefix=r.get("prefix") + ) + for r in rules.get("transitions", []) + ], + expirations=[ + ExpirationRule( + days=e["days"], + prefix=e.get("prefix") + ) + for e in rules.get("expirations", []) + ], + is_enabled=policy["is_enabled"], + created_at=policy["created_at"], + updated_at=policy["updated_at"] + ) + ) + + return result + + async def apply_lifecycle_rules(self, limit: int = 1000) -> Dict[str, int]: + """ + Apply lifecycle rules to eligible objects. + + Should be run periodically (e.g., daily). + Processes transitions and expirations. + + Returns: + Dictionary with counts of processed actions + """ + stats = { + "transitions": 0, + "expirations": 0, + "errors": 0 + } + + # Get all active policies + async with self.db.acquire() as conn: + policies = await conn.fetch( + """SELECT lp.*, b.name as bucket_name + FROM lifecycle_policies lp + JOIN buckets b ON b.id = lp.bucket_id + WHERE lp.is_enabled = TRUE""" + ) + + for policy in policies: + rules = json.loads(policy["rules"]) + + # Process transitions + for rule in rules.get("transitions", []): + transitioned = await self._apply_transition_rule( + conn, + policy["bucket_id"], + policy["bucket_name"], + rule + ) + stats["transitions"] += transitioned + + # Process expirations + for rule in rules.get("expirations", []): + expired = await self._apply_expiration_rule( + conn, + policy["bucket_id"], + policy["bucket_name"], + rule + ) + stats["expirations"] += expired + + if stats["transitions"] > 0 or stats["expirations"] > 0: + logger.info(f"Lifecycle processing complete: {stats}") + + return stats + + async def _apply_transition_rule( + self, + conn, + bucket_id: int, + bucket_name: str, + rule: dict + ) -> int: + """Apply a transition rule to eligible objects.""" + days = rule["days"] + target_class = rule["storage_class"] + prefix = rule.get("prefix") + + # Find objects eligible for transition + query = """ + UPDATE objects + SET storage_class = $1, + updated_at = NOW() + WHERE bucket_id = $2 + AND storage_class != $1 + AND modified_at < NOW() - INTERVAL '1 day' * $3 + """ + params = [target_class, bucket_id, days] + + if prefix: + query += " AND object_key LIKE $4" + params.append(f"{prefix}%") + + query += f" LIMIT {10000}" # Batch limit + + result = await conn.execute(query, *params) + count = int(result.split()[-1]) if result else 0 + + if count > 0: + logger.info( + f"Transitioned {count} objects in {bucket_name} " + f"to {target_class} (>{days} days, prefix: {prefix or '*'})" + ) + + return count + + async def _apply_expiration_rule( + self, + conn, + bucket_id: int, + bucket_name: str, + rule: dict + ) -> int: + """Apply an expiration rule to eligible objects.""" + days = rule["days"] + prefix = rule.get("prefix") + + # If versioning is enabled, create delete markers + bucket = await conn.fetchrow( + "SELECT versioning_enabled FROM buckets WHERE id = $1", + bucket_id + ) + + if bucket and bucket["versioning_enabled"]: + # Create delete markers for old versions + # But only for non-latest versions that are old enough + query = """ + INSERT INTO objects + (bucket_id, object_key, version_id, is_latest, + is_delete_marker, content_length, etag, modified_at) + SELECT bucket_id, object_key, + 'v-delete-' || encode(gen_random_bytes(16), 'hex'), + TRUE, TRUE, 0, '', NOW() + FROM ( + SELECT DISTINCT object_key + FROM objects + WHERE bucket_id = $1 + AND is_delete_marker = FALSE + AND is_latest = TRUE + AND modified_at < NOW() - INTERVAL '1 day' * $2 + """ + params = [bucket_id, days] + + if prefix: + query += " AND object_key LIKE $3" + params.append(f"{prefix}%") + + # Check if delete marker already exists + query += " EXCEPT SELECT object_key FROM objects WHERE is_delete_marker = TRUE" + + result = await conn.execute(query, *params) + count = int(result.split()[-1]) if result else 0 + + if count > 0: + logger.info(f"Created {count} delete markers in {bucket_name} (>{days} days)") + else: + # Hard delete old objects + query = "DELETE FROM objects WHERE bucket_id = $1 AND modified_at < NOW() - INTERVAL '1 day' * $2" + params = [bucket_id, days] + + if prefix: + query += " AND object_key LIKE $3" + params.append(f"{prefix}%") + + query += f" LIMIT {10000}" + + result = await conn.execute(query, *params) + count = int(result.split()[-1]) if result else 0 + + if count > 0: + logger.info(f"Deleted {count} objects from {bucket_name} (>{days} days)") + + return count + + async def get_object_lifecycle_status( + self, + object_id: int + ) -> Dict[str, Any]: + """Get lifecycle status for a specific object.""" + async with self.db.acquire() as conn: + obj = await conn.fetchrow( + """SELECT o.*, b.name as bucket_name, b.id as bucket_id + FROM objects o + JOIN buckets b ON b.id = o.bucket_id + WHERE o.id = $1""", + object_id + ) + + if not obj: + return None + + # Find applicable policies + policies = await conn.fetch( + """SELECT lp.* FROM lifecycle_policies lp + WHERE lp.bucket_id = $1 AND lp.is_enabled = TRUE""", + obj["bucket_id"] + ) + + applicable_actions = [] + + for policy in policies: + rules = json.loads(policy["rules"]) + + # Check transitions + for rule in rules.get("transitions", []): + prefix = rule.get("prefix") + if prefix and not obj["object_key"].startswith(prefix): + continue + + days_old = (datetime.now(timezone.utc) - obj["modified_at"]).days + + if days_old >= rule["days"]: + applicable_actions.append({ + "action": LifecycleAction.TRANSITION.value, + "target_storage_class": rule["storage_class"], + "eligible_since": obj["modified_at"] + timedelta(days=rule["days"]) + }) + + # Check expirations + for rule in rules.get("expirations", []): + prefix = rule.get("prefix") + if prefix and not obj["object_key"].startswith(prefix): + continue + + days_old = (datetime.now(timezone.utc) - obj["modified_at"]).days + + if days_old >= rule["days"]: + applicable_actions.append({ + "action": LifecycleAction.EXPIRE.value, + "eligible_since": obj["modified_at"] + timedelta(days=rule["days"]) + }) + + return { + "object_id": object_id, + "object_key": obj["object_key"], + "storage_class": obj["storage_class"], + "created_at": obj["created_at"].isoformat(), + "modified_at": obj["modified_at"].isoformat(), + "applicable_actions": applicable_actions + } +``` + +**Lifecycle API endpoints**: +```python +from fastapi import APIRouter, HTTPException, Query +from pydantic import BaseModel +from typing import List, Optional + +router = APIRouter(prefix="/v1/lifecycle", tags=["lifecycle"]) + +class TransitionRuleModel(BaseModel): + days: int + storage_class: str + prefix: Optional[str] = None + +class ExpirationRuleModel(BaseModel): + days: int + prefix: Optional[str] = None + +class LifecyclePolicyModel(BaseModel): + name: str + transitions: List[TransitionRuleModel] = [] + expirations: List[ExpirationRuleModel] = [] + +@router.post("/buckets/{bucket_id}/policies") +async def create_lifecycle_policy( + bucket_id: int, + policy: LifecyclePolicyModel +): + """Create a lifecycle policy for a bucket.""" + manager = get_lifecycle_manager() + + policy_id = await manager.create_policy( + bucket_id=bucket_id, + name=policy.name, + transitions=[t.dict() for t in policy.transitions], + expirations=[e.dict() for e in policy.expirations] + ) + + return {"policy_id": policy_id, "message": "Policy created"} + +@router.get("/buckets/{bucket_id}/policies") +async def list_lifecycle_policies(bucket_id: int): + """List lifecycle policies for a bucket.""" + manager = get_lifecycle_manager() + + policies = await manager.list_policies(bucket_id) + + return { + "bucket_id": bucket_id, + "policies": [ + { + "id": p.id, + "name": p.name, + "transitions": [ + { + "days": t.days, + "storage_class": t.target_storage_class.value, + "prefix": t.prefix + } + for t in p.transitions + ], + "expirations": [ + { + "days": e.days, + "prefix": e.prefix + } + for e in p.expirations + ], + "is_enabled": p.is_enabled, + "created_at": p.created_at.isoformat() if p.created_at else None + } + for p in policies + ] + } + +@router.get("/policies/{policy_id}") +async def get_lifecycle_policy(policy_id: int): + """Get a specific lifecycle policy.""" + manager = get_lifecycle_manager() + + policy = await manager.get_policy(policy_id) + + if not policy: + raise HTTPException(status_code=404, detail="Policy not found") + + return { + "id": policy.id, + "bucket_id": policy.bucket_id, + "name": policy.name, + "transitions": [ + { + "days": t.days, + "storage_class": t.target_storage_class.value, + "prefix": t.prefix + } + for t in policy.transitions + ], + "expirations": [ + { + "days": e.days, + "prefix": e.prefix + } + for e in p.expirations + ], + "is_enabled": policy.is_enabled + } + +@router.put("/policies/{policy_id}") +async def update_lifecycle_policy( + policy_id: int, + policy: LifecyclePolicyModel +): + """Update a lifecycle policy.""" + manager = get_lifecycle_manager() + + success = await manager.update_policy( + policy_id=policy_id, + name=policy.name, + transitions=[t.dict() for t in policy.transitions], + expirations=[e.dict() for e in policy.expirations] + ) + + return {"message": "Policy updated"} + +@router.delete("/policies/{policy_id}") +async def delete_lifecycle_policy(policy_id: int): + """Delete a lifecycle policy.""" + manager = get_lifecycle_manager() + + success = await manager.delete_policy(policy_id) + + if not success: + raise HTTPException(status_code=404, detail="Policy not found") + + return {"message": "Policy deleted"} + +@router.post("/apply") +async def apply_lifecycle_policies(limit: int = Query(1000)): + """Manually trigger lifecycle rule processing.""" + manager = get_lifecycle_manager() + + stats = await manager.apply_lifecycle_rules(limit=limit) + + return { + "message": "Lifecycle rules applied", + "stats": stats + } + +@router.get("/objects/{object_id}/lifecycle") +async def get_object_lifecycle_status(object_id: int): + """Get lifecycle status for an object.""" + manager = get_lifecycle_manager() + + status = await manager.get_object_lifecycle_status(object_id) + + if not status: + raise HTTPException(status_code=404, detail="Object not found") + + return status +``` + +## Acceptance Criteria + +- [ ] Policies can be created per bucket +- [ ] Objects transition storage classes automatically +- [ ] Objects expire/delete according to rules +- [ ] Prefix-based rules work +- [ ] Policies can be enabled/disabled +- [ ] Lifecycle status is visible per object +- [ ] Manual rule application works + +## Notes + +**Trade-offs**: +- Immediate vs scheduled processing: Scheduled for batch efficiency +- Hard delete vs soft delete: Depends on bucket versioning + +**Performance**: +- Process rules in batches +- Index on modified_at for efficient querying + +**Alternatives considered**: +- S3 lifecycle rules: Similar approach adopted +- Custom tags for rules: More flexible but more complex diff --git a/ai_coder_1/subtasks/Decomp-005-09.md b/ai_coder_1/subtasks/Decomp-005-09.md new file mode 100644 index 0000000..2d74e26 --- /dev/null +++ b/ai_coder_1/subtasks/Decomp-005-09.md @@ -0,0 +1,635 @@ +# Subtask: Data Integrity Verification + +**Parent Task**: Decomp/005 +**Subtask ID**: Decomp-005-09 +**Dependencies**: Decomp-005-01 (Storage Architecture), Decomp-005-04 (Data Replication Engine) + +## Description + +Implement data integrity verification system. Support checksum validation, periodic integrity scans, corruption detection, and automatic repair from replicas. + +## Requirements + +- Calculate checksums on upload (MD5, SHA-256) +- Verify checksums on download +- Periodic integrity scans +- Detect corrupted data +- Auto-repair from healthy replicas +- Report integrity metrics +- Support multiple checksum algorithms + +## Technical Specifications + +**Integrity verification service**: +```python +from typing import List, Dict, Any, Optional, Tuple +from dataclasses import dataclass +from datetime import datetime, timezone, timedelta +from enum import Enum +import hashlib +import logging + +logger = logging.getLogger(__name__) + +class ChecksumAlgorithm(Enum): + """Supported checksum algorithms.""" + MD5 = "md5" + SHA1 = "sha1" + SHA256 = "sha256" + SHA512 = "sha512" + +@dataclass +class ChecksumResult: + """Result of checksum calculation.""" + algorithm: ChecksumAlgorithm + checksum: str + bytes_processed: int + +@dataclass +class IntegrityStatus: + """Integrity status for an object.""" + object_id: int + bucket_id: int + object_key: str + expected_checksum: str + actual_checksum: str + is_valid: bool + nodes_checked: List[str] + corrupt_nodes: List[str] + healthy_nodes: List[str] + +@dataclass +class ScanResult: + """Result of an integrity scan.""" + objects_scanned: int + objects_valid: int + objects_corrupt: int + objects_missing_replicas: int + scan_duration_seconds: float + errors: List[str] + +class IntegrityVerificationService: + """Service for data integrity verification.""" + + def __init__(self, db, storage_adapter): + self.db = db + self.storage = storage_adapter + + def calculate_checksum( + self, + data: bytes, + algorithm: ChecksumAlgorithm = ChecksumAlgorithm.MD5 + ) -> ChecksumResult: + """Calculate checksum for data.""" + if algorithm == ChecksumAlgorithm.MD5: + checksum = hashlib.md5(data).hexdigest() + elif algorithm == ChecksumAlgorithm.SHA1: + checksum = hashlib.sha1(data).hexdigest() + elif algorithm == ChecksumAlgorithm.SHA256: + checksum = hashlib.sha256(data).hexdigest() + elif algorithm == ChecksumAlgorithm.SHA512: + checksum = hashlib.sha512(data).hexdigest() + else: + raise ValueError(f"Unsupported algorithm: {algorithm}") + + return ChecksumResult( + algorithm=algorithm, + checksum=checksum, + bytes_processed=len(data) + ) + + def calculate_checksum_from_file( + self, + file_path: str, + algorithm: ChecksumAlgorithm = ChecksumAlgorithm.MD5 + ) -> ChecksumResult: + """Calculate checksum for a file (streaming for large files).""" + hash_func = None + if algorithm == ChecksumAlgorithm.MD5: + hash_func = hashlib.md5() + elif algorithm == ChecksumAlgorithm.SHA256: + hash_func = hashlib.sha256() + else: + raise ValueError(f"Unsupported algorithm: {algorithm}") + + with open(file_path, "rb") as f: + for chunk in iter(lambda: f.read(8192), b""): + hash_func.update(chunk) + + return ChecksumResult( + algorithm=algorithm, + checksum=hash_func.hexdigest(), + bytes_processed=file_path.stat().st_size + ) + + async def verify_object_integrity( + self, + object_id: int + ) -> IntegrityStatus: + """ + Verify integrity of an object across all replicas. + + Reads data from each node and compares checksums. + """ + async with self.db.acquire() as conn: + obj = await conn.fetchrow( + """SELECT o.*, b.name as bucket_name + FROM objects o + JOIN buckets b ON b.id = o.bucket_id + WHERE o.id = $1""", + object_id + ) + + if not obj: + raise ValueError(f"Object {object_id} not found") + + expected_etag = obj["etag"] + storage_nodes = json.loads(obj.get("storage_nodes", "[]")) + bucket_name = obj["bucket_name"] + object_key = obj["object_key"] + + # Read and verify from each node + healthy_nodes = [] + corrupt_nodes = [] + + for node_id in storage_nodes: + try: + file_path = f"{bucket_name}/{object_key}" + data = await self.storage.read_file(node_id, file_path) + + # Calculate checksum + actual_etag = hashlib.md5(data).hexdigest() + + if actual_etag == expected_etag: + healthy_nodes.append(node_id) + else: + logger.error( + f"Checksum mismatch for object {object_id} " + f"on node {node_id}: expected {expected_etag}, got {actual_etag}" + ) + corrupt_nodes.append(node_id) + + except Exception as e: + logger.error(f"Failed to read object {object_id} from node {node_id}: {e}") + corrupt_nodes.append(node_id) + + is_valid = len(healthy_nodes) > 0 + # Consider valid if at least one replica is healthy + + # Record verification result + async with self.db.acquire() as conn: + await conn.execute( + """INSERT INTO integrity_checks + (object_id, checksum_algorithm, expected_checksum, is_valid, + healthy_nodes, corrupt_nodes, checked_at) + VALUES ($1, 'md5', $2, $3, $4, $5, NOW())""", + object_id, expected_etag, is_valid, + healthy_nodes, corrupt_nodes + ) + + return IntegrityStatus( + object_id=object_id, + bucket_id=obj["bucket_id"], + object_key=object_key, + expected_checksum=expected_etag, + actual_checksum=expected_etag if is_valid else "MISMATCH", + is_valid=is_valid, + nodes_checked=storage_nodes, + corrupt_nodes=corrupt_nodes, + healthy_nodes=healthy_nodes + ) + + async def scan_bucket_integrity( + self, + bucket_id: int, + sample_size: int = 1000, + repair_corrupted: bool = True + ) -> ScanResult: + """ + Scan bucket for integrity issues. + + Args: + bucket_id: Bucket to scan + sample_size: Number of objects to check (for large buckets) + repair_corrupted: Attempt to repair corrupted objects + + Returns: + ScanResult with statistics + """ + start_time = datetime.now(timezone.utc) + + objects_scanned = 0 + objects_valid = 0 + objects_corrupt = 0 + objects_missing_replicas = 0 + errors = [] + + async with self.db.acquire() as conn: + # Get sample of objects + objects = await conn.fetch( + """SELECT o.id, o.bucket_id, o.object_key, o.storage_nodes, o.etag, + COUNT(r.id) as replica_count + FROM objects o + LEFT JOIN replication_status r ON r.object_id = o.id AND r.status = 'completed' + WHERE o.bucket_id = $1 + AND o.is_delete_marker = FALSE + GROUP BY o.id + ORDER BY RANDOM() + LIMIT $2""", + bucket_id, sample_size + ) + + for obj in objects: + objects_scanned += 1 + + try: + status = await self.verify_object_integrity(obj["id"]) + + if status.is_valid: + objects_valid += 1 + + # Check if we have enough replicas + expected_replicas = 3 + actual_replicas = len(status.healthy_nodes) + + if actual_replicas < expected_replicas: + objects_missing_replicas += 1 + + if repair_corrupted: + await self._repair_object(obj["id"], status) + else: + objects_corrupt += 1 + + if repair_corrupted: + await self._repair_object(obj["id"], status) + + except Exception as e: + errors.append(f"{obj['id']}: {str(e)}") + logger.error(f"Error checking object {obj['id']}: {e}") + + duration = (datetime.now(timezone.utc) - start_time).total_seconds() + + return ScanResult( + objects_scanned=objects_scanned, + objects_valid=objects_valid, + objects_corrupt=objects_corrupt, + objects_missing_replicas=objects_missing_replicas, + scan_duration_seconds=duration, + errors=errors + ) + + async def _repair_object( + self, + object_id: int, + status: IntegrityStatus + ): + """ + Repair a corrupted object from healthy replicas. + + Copies data from healthy nodes to corrupt/missing nodes. + """ + if not status.healthy_nodes: + logger.error(f"Cannot repair object {object_id}: no healthy replicas") + return + + source_node = status.healthy_nodes[0] + + # Get object details + async with self.db.acquire() as conn: + obj = await conn.fetchrow( + """SELECT o.*, b.name as bucket_name + FROM objects o + JOIN buckets b ON b.id = o.bucket_id + WHERE o.id = $1""", + object_id + ) + + # Read from healthy node + file_path = f"{obj['bucket_name']}/{obj['object_key']}" + data = await self.storage.read_file(source_node, file_path) + + # Write to corrupt/missing nodes + repaired = 0 + + for node_id in status.corrupt_nodes: + try: + await self.storage.write_file( + node_id=node_id, + bucket_name=obj["bucket_name"], + object_key=obj["object_key"], + data=data + ) + repaired += 1 + logger.info(f"Repaired object {object_id} on node {node_id}") + + except Exception as e: + logger.error(f"Failed to repair object {object_id} on node {node_id}: {e}") + + # Record repair + async with self.db.acquire() as conn: + await conn.execute( + """INSERT INTO integrity_repairs + (object_id, corrupt_nodes, repaired_nodes, repaired_at) + VALUES ($1, $2, $3, NOW())""", + object_id, status.corrupt_nodes, + status.corrupt_nodes[:repaired] # Simplified + ) + + logger.info(f"Repaired {repaired} replicas for object {object_id}") + + async def get_integrity_metrics( + self, + bucket_id: int = None + ) -> Dict[str, Any]: + """Get integrity metrics for a bucket or all objects.""" + async with self.db.acquire() as conn: + query = """ + SELECT + COUNT(*) as total_objects, + COUNT(*) FILTER (WHERE checksum_sha256 IS NOT NULL) as has_sha256, + COUNT(*) FILTER (WHERE etag IS NOT NULL) as has_md5 + FROM objects + """ + params = [] + + if bucket_id: + query += " WHERE bucket_id = $1" + params.append(bucket_id) + + stats = await conn.fetchrow(query, *params) + + # Get recent scan results + scan_query = """ + SELECT + COUNT(*) FILTER (WHERE is_valid = TRUE) as valid_checks, + COUNT(*) FILTER (WHERE is_valid = FALSE) as invalid_checks, + COUNT(*) as total_checks, + MAX(checked_at) as last_check + FROM integrity_checks + """ + scan_params = [] + + if bucket_id: + scan_query += " WHERE object_id IN (SELECT id FROM objects WHERE bucket_id = $1)" + scan_params.append(bucket_id) + + scan_stats = await conn.fetchrow(scan_query, *scan_params) + + return { + "total_objects": stats["total_objects"] or 0, + "objects_with_sha256": stats["has_sha256"] or 0, + "objects_with_md5": stats["has_md5"] or 0, + "total_integrity_checks": scan_stats["total_checks"] or 0, + "valid_checks": scan_stats["valid_checks"] or 0, + "invalid_checks": scan_stats["invalid_checks"] or 0, + "last_check": scan_stats["last_check"].isoformat() if scan_stats["last_check"] else None, + "integrity_health_percent": round( + (scan_stats["valid_checks"] / scan_stats["total_checks"] * 100) + if scan_stats["total_checks"] > 0 else 100, + 2 + ) + } + + async def get_corrupted_objects( + self, + bucket_id: int = None, + limit: int = 100 + ) -> List[IntegrityStatus]: + """Get list of objects that failed integrity checks.""" + async with self.db.acquire() as conn: + query = """ + SELECT ic.object_id, o.bucket_id, o.object_key, + ic.expected_checksum, ic.is_valid, + ic.healthy_nodes, ic.corrupt_nodes + FROM integrity_checks ic + JOIN objects o ON o.id = ic.object_id + WHERE ic.is_valid = FALSE + """ + params = [] + + if bucket_id: + query += " AND o.bucket_id = $1" + params.append(bucket_id) + + query += f" ORDER BY ic.checked_at DESC LIMIT {limit}" + + rows = await conn.fetch(query, *params) + + return [ + IntegrityStatus( + object_id=r["object_id"], + bucket_id=r["bucket_id"], + object_key=r["object_key"], + expected_checksum=r["expected_checksum"], + actual_checksum="CORRUPT", + is_valid=False, + nodes_checked=json.loads(r.get("healthy_nodes") or "[]"), + corrupt_nodes=json.loads(r.get("corrupt_nodes") or "[]"), + healthy_nodes=json.loads(r.get("healthy_nodes") or "[]") + ) + for r in rows + ] +``` + +**Database schema extensions**: +```sql +-- Integrity checks log +CREATE TABLE integrity_checks ( + id BIGSERIAL PRIMARY KEY, + object_id BIGINT NOT NULL REFERENCES objects(id) ON DELETE CASCADE, + checksum_algorithm VARCHAR(20) NOT NULL DEFAULT 'md5', + expected_checksum VARCHAR(200) NOT NULL, + actual_checksum VARCHAR(200), + is_valid BOOLEAN NOT NULL, + healthy_nodes JSONB DEFAULT '[]'::jsonb, + corrupt_nodes JSONB DEFAULT '[]'::jsonb, + checked_at TIMESTAMP NOT NULL DEFAULT NOW() +); + +CREATE INDEX idx_integrity_checks_object ON integrity_checks(object_id); +CREATE INDEX idx_integrity_checks_valid ON integrity_checks(is_valid, checked_at) + WHERE is_valid = FALSE; + +-- Integrity repairs log +CREATE TABLE integrity_repairs ( + id BIGSERIAL PRIMARY KEY, + object_id BIGINT NOT NULL REFERENCES objects(id) ON DELETE CASCADE, + corrupt_nodes JSONB NOT NULL, + repaired_nodes JSONB NOT NULL, + repair_method VARCHAR(50) DEFAULT 'replica_copy', + repaired_at TIMESTAMP NOT NULL DEFAULT NOW(), + metadata JSONB DEFAULT '{}'::jsonb +); + +CREATE INDEX idx_integrity_repairs_object ON integrity_repairs(object_id); +``` + +**Integrity monitoring API**: +```python +from fastapi import APIRouter, HTTPException, Query + +router = APIRouter(prefix="/v1/integrity", tags=["integrity"]) + +@router.get("/metrics") +async def get_integrity_metrics( + bucket_id: Optional[int] = None +): + """Get integrity metrics.""" + service = get_integrity_service() + return await service.get_integrity_metrics(bucket_id) + +@router.post("/scan/{bucket_id}") +async def scan_bucket_integrity( + bucket_id: int, + sample_size: int = Query(1000, ge=1, le=10000), + repair_corrupted: bool = True +): + """Scan a bucket for integrity issues.""" + service = get_integrity_service() + + result = await service.scan_bucket_integrity( + bucket_id=bucket_id, + sample_size=sample_size, + repair_corrupted=repair_corrupted + ) + + return { + "bucket_id": bucket_id, + "scan_result": { + "objects_scanned": result.objects_scanned, + "objects_valid": result.objects_valid, + "objects_corrupt": result.objects_corrupt, + "objects_missing_replicas": result.objects_missing_replicas, + "scan_duration_seconds": round(result.scan_duration_seconds, 2), + "errors": result.errors[:10] # First 10 errors + } + } + +@router.get("/objects/{object_id}/integrity") +async def verify_object_integrity(object_id: int): + """Verify integrity of a specific object.""" + service = get_integrity_service() + + try: + status = await service.verify_object_integrity(object_id) + return { + "object_id": status.object_id, + "object_key": status.object_key, + "is_valid": status.is_valid, + "expected_checksum": status.expected_checksum, + "nodes_checked": status.nodes_checked, + "healthy_nodes": status.healthy_nodes, + "corrupt_nodes": status.corrupt_nodes + } + except ValueError as e: + raise HTTPException(status_code=404, detail=str(e)) + +@router.get("/corrupted") +async def list_corrupted_objects( + bucket_id: Optional[int] = None, + limit: int = Query(100) +): + """Get list of corrupted objects.""" + service = get_integrity_service() + + corrupted = await service.get_corrupted_objects(bucket_id, limit) + + return { + "corrupted_objects": [ + { + "object_id": c.object_id, + "object_key": c.object_key, + "bucket_id": c.bucket_id, + "expected_checksum": c.expected_checksum, + "healthy_nodes": c.healthy_nodes, + "corrupt_nodes": c.corrupt_nodes + } + for c in corrupted + ] + } +``` + +**Background integrity scanner**: +```python +class IntegrityScanner: + """Background scanner for periodic integrity checks.""" + + def __init__( + self, + integrity_service: IntegrityVerificationService, + scan_interval_hours: int = 24 + ): + self.integrity_service = integrity_service + self.scan_interval = timedelta(hours=scan_interval_hours) + self.task: Optional[asyncio.Task] = None + + async def start(self): + """Start the background scanner.""" + self.task = asyncio.create_task(self._scan_loop()) + logger.info("Integrity scanner started") + + async def stop(self): + """Stop the background scanner.""" + if self.task: + self.task.cancel() + try: + await self.task + except asyncio.CancelledError: + pass + + logger.info("Integrity scanner stopped") + + async def _scan_loop(self): + """Periodic scan loop.""" + while True: + try: + # Get all active buckets + async with self.integrity_service.db.acquire() as conn: + buckets = await conn.fetch( + "SELECT id FROM buckets WHERE is_active = TRUE" + ) + + for bucket in buckets: + try: + # Scan a sample of each bucket + await self.integrity_service.scan_bucket_integrity( + bucket_id=bucket["id"], + sample_size=1000, # Sample size per run + repair_corrupted=True + ) + except Exception as e: + logger.error(f"Error scanning bucket {bucket['id']}: {e}") + + # Wait until next scan + await asyncio.sleep(self.scan_interval.total_seconds()) + + except asyncio.CancelledError: + break + except Exception as e: + logger.error(f"Error in scan loop: {e}") + await asyncio.sleep(60) # Wait 1 minute on error +``` + +## Acceptance Criteria + +- [ ] Checksums are calculated on upload +- [ ] Checksums are verified on download +- [ ] Integrity scans detect corruption +- [ ] Corrupted objects are auto-repaired +- [ ] Integrity metrics are tracked +- [ ] Background scanner runs periodically +- [ ] Corrupted objects can be listed + +## Notes + +**Trade-offs**: +- Full vs sample scanning: Sample for performance +- Immediate vs deferred repair: Immediate for data safety + +**Performance**: +- Parallelize checksum calculations +- Scan different regions separately + +**Alternatives considered**: +- ZFS-style end-to-end checksums: Overkill for this system +- Merkle trees: Too complex for object-level diff --git a/ai_coder_1/tasks.json b/ai_coder_1/tasks.json new file mode 100644 index 0000000..02f0827 --- /dev/null +++ b/ai_coder_1/tasks.json @@ -0,0 +1,172 @@ +{ + "tasks": [ + { + "task_id": "Decomp/001", + "title": "URL Shortener Service (bit.ly clone)", + "difficulty": "Hard", + "description": "Design a production-ready URL shortener service like bit.ly or tinyurl.com", + "requirements": [ + "Generate short codes (6-8 characters) from long URLs", + "Handle redirects with HTTP 301/302", + "Custom alias support (users can choose their short code)", + "QR code generation for short URLs", + "Link expiration with TTL", + "Analytics: click count, timestamp, user-agent, geo-location" + ], + "non_functional": [ + "10M URLs in database", + "100K requests/second throughput", + "99.9% availability", + "<50ms p95 latency for redirects", + "Handle duplicate URL detection" + ], + "constraints": [ + "Base62 encoding for short codes", + "No external dependencies for core logic", + "Must handle hash collisions gracefully" + ], + "considerations": [ + "How to generate unique short codes at scale?", + "How to handle hash collisions?", + "Database schema design (SQL vs NoSQL)?", + "Caching strategy (Redis)?", + "Rate limiting for abuse prevention?" + ] + }, + { + "task_id": "Decomp/002", + "title": "Real-Time Chat Service (Discord/Slack clone)", + "difficulty": "Hard", + "description": "Design a real-time messaging platform supporting multiple channels and online presence", + "requirements": [ + "Real-time message delivery using WebSockets", + "Multiple channels/servers per user", + "Message history with pagination", + "User online/offline status", + "Direct messages (DM) between users", + "Message reactions and emojis", + "File attachments (images, documents)", + "Message search functionality" + ], + "non_functional": [ + "100K concurrent connections", + "<100ms message delivery latency", + "99.95% availability", + "Persistent message storage" + ], + "constraints": [ + "Message ordering must be preserved", + "Handle network reconnection gracefully", + "Support both WebSocket and HTTP fallback" + ], + "considerations": [ + "Message broker choice (Kafka vs RabbitMQ)?", + "How to handle user presence across devices?", + "Message storage optimization (hot vs cold data)?", + "Scaling WebSocket connections?" + ] + }, + { + "task_id": "Decomp/003", + "title": "Distributed Task Queue (Celery/RQ clone)", + "difficulty": "Hard", + "description": "Build a distributed task execution system with worker pools and result storage", + "requirements": [ + "Task scheduling with priorities", + "Retrying failed tasks with exponential backoff", + "Task chaining and workflows (DAG)", + "Periodic/cron-like tasks", + "Task result storage and retrieval", + "Worker health monitoring and auto-recovery", + "Task cancellation support", + "Rate limiting per task type" + ], + "non_functional": [ + "1M tasks/day throughput", + "Horizontal scaling of workers", + "Fault tolerance (broker/worker failures)", + "<1s task scheduling latency" + ], + "constraints": [ + "At-least-once delivery semantics", + "No duplicate task execution", + "Support both sync and async task execution" + ], + "considerations": [ + "Message broker choice (Redis vs RabbitMQ vs Kafka)?", + "Task serialization format?", + "How to handle long-running tasks?", + "Worker scaling strategy?", + "Dead letter queue handling?" + ] + }, + { + "task_id": "Decomp/004", + "title": "E-Commerce Order Processing System", + "difficulty": "Hard", + "description": "Design a robust order processing pipeline handling inventory, payments, and fulfillment", + "requirements": [ + "Shopping cart management", + "Inventory reservation and locking", + "Payment integration (multiple providers)", + "Order status workflow (pending\u2192paid\u2192shipped\u2192delivered)", + "Shipping label generation", + "Order cancellation and refund handling", + "Notification system (email/SMS)", + "Order history and analytics" + ], + "non_functional": [ + "Handle 10K orders/minute peak", + "Exactly-once inventory deduction", + "Payment transaction consistency", + "<200ms checkout flow latency" + ], + "constraints": [ + "ACID properties for order-inventory operations", + "Idempotent payment processing", + "Handle payment failures gracefully" + ], + "considerations": [ + "How to prevent race conditions in inventory?", + "Distributed transaction pattern (Saga vs 2PC)?", + "Payment provider fallback strategy?", + "Order event sourcing for audit trail?" + ] + }, + { + "task_id": "Decomp/005", + "title": "Distributed File Storage System (S3 clone)", + "difficulty": "Hard", + "description": "Design a scalable object storage service with durability and availability guarantees", + "requirements": [ + "File upload/download with chunking", + "Bucket-based organization", + "Access control (ACLs, presigned URLs)", + "File versioning", + "Multi-part upload for large files", + "Automatic replication across nodes", + "Data integrity verification (checksums)", + "Lifecycle policies (expiration, archival)" + ], + "non_functional": [ + "99.999999999% durability (11 9's)", + "99.99% availability", + "Petabyte-scale storage", + "Unlimited file size support", + "<100ms upload latency p95" + ], + "constraints": [ + "Eventually consistent metadata", + "Strong consistency for reads-after-writes", + "No single point of failure" + ], + "considerations": [ + "Erasure coding vs replication?", + "Consistent hashing for data distribution?", + "How to handle node failures?", + "Metadata database design?", + "Storage backend (local filesystem vs object storage)?" + ] + } + ] +} \ No newline at end of file diff --git a/ai_coder_2/.DS_Store b/ai_coder_2/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..57b964a64d9550f92af749aa581ba929895e53d4 GIT binary patch literal 6148 zcmeHKy-EW?5S}%Wga{I_u@Sbk%^RHI)K&=gdI_j_;euzXAYAPmXzQEU_zpgYg{9x@ z4Dl{^{!}7512f-dcV>3xgWJs#ksHn@1EM|=b)k&y9!!JqI%`eVbY>IiLXH_-Q$ESZ zX_D2vZNeBZ27Vg@{Oxuqr!ig81(m+vEag&HmeRAqXq-)F(#6hw-D8@?agt^UR=T^3 z&db5w(_WL;bnZG^Yf|%qd2flvgWyJ#O+T*YvnPzde+iYPqJ_dsUzL zRqAp_Tvv}4tCi7>9E3t-qeHcL&eNQz+`x0|VQVN2H0CTf@s)3-k+8j)f5ZUpY?khZ zpjl(U7%&Ew4Dk8jp^TAYAsCJhnD7JuwlN(9V}46;j8}{l3qhcDnl%QDfhq$n`Pt|DfB)n6e>KQ{83V?^pJKqZ z<54_BOM17~n&Z3HLr{kee5E#9V!+@{iZD5c?w#XfR_8{3ru& DZ<~bX literal 0 HcmV?d00001 diff --git a/ai_coder_2/PROMPT.md b/ai_coder_2/PROMPT.md new file mode 100644 index 0000000..dccf01c --- /dev/null +++ b/ai_coder_2/PROMPT.md @@ -0,0 +1,139 @@ +# Architect Role Instructions + +**You are an Architect (LLM specializing in task decomposition). Your job is NOT to write code, but to break down complex system design tasks into clear, implementable subtasks.** + +## Your Workflow + +### 1. Read the Task +Read `tasks.json` in your directory. Pick the next uncompleted task (check `subtasks/` folder). + +### 2. Start Timer +Create `start_time.txt` with current timestamp (ISO 8601): +```python +from datetime import datetime +with open("start_time.txt", "w") as f: + f.write(datetime.utcnow().isoformat()) +``` + +### 3. Decompose the Task +Break down the task into 5-15 subtasks. For each subtask, create a detailed specification. + +**Decomposition principles**: +- Each subtask should be independently implementable by a Coder LLM +- Subtasks should have minimal dependencies on each other +- Complex subtasks should be further broken down +- Order subtasks logically (data layer → business logic → API → extras) + +### 4. Save Subtasks +For each subtask, create a markdown file in `subtasks/{task_id}.md` (e.g., `subtasks/Decomp/001-01.md`). + +**Subtask template**: +```markdown +# Subtask: {Title} + +**Parent Task**: {task_id} +**Subtask ID**: {task_id}-{number} +**Dependencies**: {list of subtask IDs this depends on} + +## Description +{Clear description of what this subtask implements} + +## Requirements +- {Functional requirement 1} +- {Functional requirement 2} + +## Technical Specifications +- {Algorithm choice} +- {Data structures} +- {API signatures} +- {Error handling} + +## Acceptance Criteria +- [ ] {Testable criterion 1} +- [ ] {Testable criterion 2} + +## Notes +{Edge cases, trade-offs, alternatives considered} +``` + +### 5. Stop Timer and Save Results +Calculate elapsed time and save results: + +```python +from datetime import datetime +import json + +with open("start_time.txt") as f: + start_time = datetime.fromisoformat(f.read()) +elapsed_time = (datetime.utcnow() - start_time).total_seconds() + +result = { + "task_id": task_id, + "architect": f"ai_coder_{N}", + "elapsed_time_seconds": elapsed_time, + "subtask_count": len(subtasks), + "subtasks": [list of subtask files] +} + +with open("result.json", "w") as f: + json.dump(result, f, indent=2) + +with open("result.txt", "w") as f: + f.write(f"Task: {task_id}\n") + f.write(f"Architect: ai_coder_{N}\n") + f.write(f"Time: {elapsed_time:.2f}s\n") + f.write(f"Subtasks: {len(subtasks)}\n") +``` + +## Decomposition Quality Checklist + +Before finishing, verify your decomposition: + +✅ **Granularity**: Each subtask is implementable in 1-2 hours by a Coder LLM +✅ **Independence**: Subtasks have minimal cross-dependencies +✅ **Clarity**: Each subtask has unambiguous requirements +✅ **Completeness**: All parent task requirements are covered +✅ **Ordering**: Subtasks are ordered for logical implementation +✅ **Testability**: Each subtask has verifiable acceptance criteria + +## Example: Good vs Bad Decomposition + +### ❌ Bad: Too coarse +``` +Subtask 1: "Build the URL shortener" +``` +- Not implementable in one step +- Lacks detail +- No clear acceptance criteria + +### ✅ Good: Properly decomposed +``` +Subtask 1: "Design database schema for URL storage" +- Defines tables, indexes, relationships + +Subtask 2: "Implement Base62 encoding/decoding" +- Clear algorithm specification +- Independent of database + +Subtask 3: "Generate unique short codes with collision handling" +- Combines encoding with uniqueness logic +- Has clear acceptance criteria + +Subtask 4: "Implement HTTP redirect endpoint" +- Clear API specification +- Depends on Subtask 1 and 3 +``` + +## Important Notes + +1. **You are NOT writing code** — you are creating detailed specifications for others to implement +2. **Think like a tech lead** — consider scalability, reliability, and maintainability +3. **Be specific** — don't say "implement caching", say "use Redis with LRU eviction and 1-hour TTL" +4. **Consider edge cases** — what happens when X fails? What about concurrent operations? +5. **Document trade-offs** — why did you choose approach A over B? + +## Available Information + +- Task details in `tasks.json` +- Write subtasks to `subtasks/` directory +- Save results to `result.json` and `result.txt` diff --git a/ai_coder_2/result.json b/ai_coder_2/result.json new file mode 100644 index 0000000..f0744f9 --- /dev/null +++ b/ai_coder_2/result.json @@ -0,0 +1,20 @@ +{ + "task_id": "Decomp/001", + "architect": "ai_coder_2", + "elapsed_time_seconds": 409.41, + "subtask_count": 12, + "subtasks": [ + "Decomp/001-01.md", + "Decomp/001-02.md", + "Decomp/001-03.md", + "Decomp/001-04.md", + "Decomp/001-05.md", + "Decomp/001-06.md", + "Decomp/001-07.md", + "Decomp/001-08.md", + "Decomp/001-09.md", + "Decomp/001-10.md", + "Decomp/001-11.md", + "Decomp/001-12.md" + ] +} \ No newline at end of file diff --git a/ai_coder_2/result.txt b/ai_coder_2/result.txt new file mode 100644 index 0000000..58f4326 --- /dev/null +++ b/ai_coder_2/result.txt @@ -0,0 +1,18 @@ +Task: Decomp/001 +Architect: ai_coder_2 +Time: 409.41s +Subtasks: 12 + +Subtask files: + - Decomp/001-01.md + - Decomp/001-02.md + - Decomp/001-03.md + - Decomp/001-04.md + - Decomp/001-05.md + - Decomp/001-06.md + - Decomp/001-07.md + - Decomp/001-08.md + - Decomp/001-09.md + - Decomp/001-10.md + - Decomp/001-11.md + - Decomp/001-12.md diff --git a/ai_coder_2/scripts/load_tasks.py b/ai_coder_2/scripts/load_tasks.py new file mode 100644 index 0000000..ad928ce --- /dev/null +++ b/ai_coder_2/scripts/load_tasks.py @@ -0,0 +1,197 @@ +#!/usr/bin/env python3 +""" +Load complex architectural decomposition tasks into tasks.json +""" + +import json +from pathlib import Path + +# СЛОЖНЫЕ ЗАДАЧИ ДЛЯ ДЕКОМПОЗИЦИИ +# Каждый Architect получит эти задачи и должен разбить их на подзадачи + +ARCHITECT_TASKS = [ + { + "task_id": "Decomp/001", + "title": "URL Shortener Service (bit.ly clone)", + "difficulty": "Hard", + "description": "Design a production-ready URL shortener service like bit.ly or tinyurl.com", + "requirements": [ + "Generate short codes (6-8 characters) from long URLs", + "Handle redirects with HTTP 301/302", + "Custom alias support (users can choose their short code)", + "QR code generation for short URLs", + "Link expiration with TTL", + "Analytics: click count, timestamp, user-agent, geo-location" + ], + "non_functional": [ + "10M URLs in database", + "100K requests/second throughput", + "99.9% availability", + "<50ms p95 latency for redirects", + "Handle duplicate URL detection" + ], + "constraints": [ + "Base62 encoding for short codes", + "No external dependencies for core logic", + "Must handle hash collisions gracefully" + ], + "considerations": [ + "How to generate unique short codes at scale?", + "How to handle hash collisions?", + "Database schema design (SQL vs NoSQL)?", + "Caching strategy (Redis)?", + "Rate limiting for abuse prevention?" + ] + }, + { + "task_id": "Decomp/002", + "title": "Real-Time Chat Service (Discord/Slack clone)", + "difficulty": "Hard", + "description": "Design a real-time messaging platform supporting multiple channels and online presence", + "requirements": [ + "Real-time message delivery using WebSockets", + "Multiple channels/servers per user", + "Message history with pagination", + "User online/offline status", + "Direct messages (DM) between users", + "Message reactions and emojis", + "File attachments (images, documents)", + "Message search functionality" + ], + "non_functional": [ + "100K concurrent connections", + "<100ms message delivery latency", + "99.95% availability", + "Persistent message storage" + ], + "constraints": [ + "Message ordering must be preserved", + "Handle network reconnection gracefully", + "Support both WebSocket and HTTP fallback" + ], + "considerations": [ + "Message broker choice (Kafka vs RabbitMQ)?", + "How to handle user presence across devices?", + "Message storage optimization (hot vs cold data)?", + "Scaling WebSocket connections?" + ] + }, + { + "task_id": "Decomp/003", + "title": "Distributed Task Queue (Celery/RQ clone)", + "difficulty": "Hard", + "description": "Build a distributed task execution system with worker pools and result storage", + "requirements": [ + "Task scheduling with priorities", + "Retrying failed tasks with exponential backoff", + "Task chaining and workflows (DAG)", + "Periodic/cron-like tasks", + "Task result storage and retrieval", + "Worker health monitoring and auto-recovery", + "Task cancellation support", + "Rate limiting per task type" + ], + "non_functional": [ + "1M tasks/day throughput", + "Horizontal scaling of workers", + "Fault tolerance (broker/worker failures)", + "<1s task scheduling latency" + ], + "constraints": [ + "At-least-once delivery semantics", + "No duplicate task execution", + "Support both sync and async task execution" + ], + "considerations": [ + "Message broker choice (Redis vs RabbitMQ vs Kafka)?", + "Task serialization format?", + "How to handle long-running tasks?", + "Worker scaling strategy?", + "Dead letter queue handling?" + ] + }, + { + "task_id": "Decomp/004", + "title": "E-Commerce Order Processing System", + "difficulty": "Hard", + "description": "Design a robust order processing pipeline handling inventory, payments, and fulfillment", + "requirements": [ + "Shopping cart management", + "Inventory reservation and locking", + "Payment integration (multiple providers)", + "Order status workflow (pending→paid→shipped→delivered)", + "Shipping label generation", + "Order cancellation and refund handling", + "Notification system (email/SMS)", + "Order history and analytics" + ], + "non_functional": [ + "Handle 10K orders/minute peak", + "Exactly-once inventory deduction", + "Payment transaction consistency", + "<200ms checkout flow latency" + ], + "constraints": [ + "ACID properties for order-inventory operations", + "Idempotent payment processing", + "Handle payment failures gracefully" + ], + "considerations": [ + "How to prevent race conditions in inventory?", + "Distributed transaction pattern (Saga vs 2PC)?", + "Payment provider fallback strategy?", + "Order event sourcing for audit trail?" + ] + }, + { + "task_id": "Decomp/005", + "title": "Distributed File Storage System (S3 clone)", + "difficulty": "Hard", + "description": "Design a scalable object storage service with durability and availability guarantees", + "requirements": [ + "File upload/download with chunking", + "Bucket-based organization", + "Access control (ACLs, presigned URLs)", + "File versioning", + "Multi-part upload for large files", + "Automatic replication across nodes", + "Data integrity verification (checksums)", + "Lifecycle policies (expiration, archival)" + ], + "non_functional": [ + "99.999999999% durability (11 9's)", + "99.99% availability", + "Petabyte-scale storage", + "Unlimited file size support", + "<100ms upload latency p95" + ], + "constraints": [ + "Eventually consistent metadata", + "Strong consistency for reads-after-writes", + "No single point of failure" + ], + "considerations": [ + "Erasure coding vs replication?", + "Consistent hashing for data distribution?", + "How to handle node failures?", + "Metadata database design?", + "Storage backend (local filesystem vs object storage)?" + ] + } +] + + +def load_tasks(): + """Load tasks into tasks.json""" + ai_coder_dir = Path(__file__).parent.parent + tasks_file = ai_coder_dir / "tasks.json" + + with open(tasks_file, 'w') as f: + json.dump({"tasks": ARCHITECT_TASKS}, f, indent=2) + + print(f"✅ Loaded {len(ARCHITECT_TASKS)} tasks to {tasks_file}") + print(f"📁 Tasks will be decomposed into: {ai_coder_dir / 'subtasks/'}") + + +if __name__ == "__main__": + load_tasks() diff --git a/ai_coder_2/start_time.txt b/ai_coder_2/start_time.txt new file mode 100644 index 0000000..4ed0277 --- /dev/null +++ b/ai_coder_2/start_time.txt @@ -0,0 +1 @@ +2026-02-03T20:15:35.173181 diff --git a/ai_coder_2/subtasks/.DS_Store b/ai_coder_2/subtasks/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..d0f77e8ebec7d68d77a9db2eb80d3c4d2e7760b5 GIT binary patch literal 6148 zcmeHK%}N6?5T4N@D_)8xFG3!{UOcBIf>-GaNL$fEmtBzF^BTU7;A?pB1$+a)$&AHy zb1ot?kbIN*+uaW~$q*4QcAFW|l!zJ(K^CPVVy?Q5EO-LsQlq7Q`#4*!ySA?s`imxc z_Y+F=Kx^t~^#1R6zx{2O(rVkSU~fL3FRyQ3-sa<&%|7P*_2aY_(?9*-iLX$?#Tjr0 zoB?OR88`?7II~5XGew`B0cXG&*fSveL%hFP&}9hgcB0F-NV5$MuONKP<}hFK9F z2x}@(Q`uS!)^yl|#YMxcsOiMke6T(FyLsXAbkq+eoH#1_>mr`aC&n1I9guh{R=4AkYVw04!u5xhPKc2hkB14YQ(D T5qn7o`bD4+;*&FQ00zDQtX(Xq literal 0 HcmV?d00001 diff --git a/ai_coder_2/subtasks/Decomp/001-01.md b/ai_coder_2/subtasks/Decomp/001-01.md new file mode 100644 index 0000000..78d0f30 --- /dev/null +++ b/ai_coder_2/subtasks/Decomp/001-01.md @@ -0,0 +1,87 @@ +# Subtask: Database Schema Design + +**Parent Task**: Decomp/001 +**Subtask ID**: Decomp/001-01 +**Dependencies**: None + +## Description +Design and implement the database schema for URL storage, including tables for URLs, analytics, and rate limiting. Support 10M URLs with proper indexing for fast lookups. + +## Requirements +- Store original URLs, short codes, custom aliases +- Support link expiration with TTL +- Track creation timestamp and access counts +- Handle duplicate URL detection efficiently +- Support composite indexes for common query patterns + +## Technical Specifications + +### Technology Stack +- **Database**: PostgreSQL (for ACID guarantees and complex queries) +- **Connection Pooling**: pgbouncer or connection pooler + +### Schema Tables + +```sql +-- URLs table +CREATE TABLE urls ( + id BIGSERIAL PRIMARY KEY, + short_code VARCHAR(8) UNIQUE NOT NULL, + original_url TEXT NOT NULL, + custom_alias BOOLEAN DEFAULT FALSE, + created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + expires_at TIMESTAMP WITH TIME ZONE, + access_count BIGINT DEFAULT 0, + checksum VARCHAR(64) -- For duplicate detection +); + +-- Indexes +CREATE INDEX idx_short_code ON urls(short_code); +CREATE INDEX idx_checksum ON urls(checksum); +CREATE INDEX idx_expires_at ON urls(expires_at) WHERE expires_at IS NOT NULL; + +-- Analytics table (separate for performance) +CREATE TABLE url_analytics ( + id BIGSERIAL PRIMARY KEY, + url_id BIGINT REFERENCES urls(id) ON DELETE CASCADE, + clicked_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + user_agent TEXT, + ip_address INET, + country_code CHAR(2), + city VARCHAR(100), + referrer TEXT +); + +CREATE INDEX idx_url_id_clicked ON url_analytics(url_id, clicked_at DESC); + +-- Rate limiting table +CREATE TABLE rate_limits ( + id BIGSERIAL PRIMARY KEY, + identifier VARCHAR(255) NOT NULL, -- IP or API key + action VARCHAR(50) NOT NULL, -- 'create', 'redirect' + window_start TIMESTAMP WITH TIME ZONE DEFAULT NOW(), + request_count INTEGER DEFAULT 1, + PRIMARY KEY (identifier, action, window_start) +); +``` + +### Data Structures +- **checksum**: SHA-256 hash of original URL for duplicate detection +- **short_code**: Base62 encoded ID (6-8 characters) + +## Acceptance Criteria +- [ ] Schema SQL file created with all tables and indexes +- [ ] Migration script for schema creation +- [ ] Foreign key constraints properly defined +- [ ] Indexes cover all query patterns (short_code lookup, duplicate detection, expiration cleanup) +- [ ] Support for 10M+ rows without performance degradation + +## Notes +- **Trade-off**: Chose SQL over NoSQL for strong consistency and transaction support +- **Scaling**: Consider partitioning by date for analytics table at 100M+ rows +- **Cleanup**: Need background job for expired URL deletion (subtask dependency) + +## Edge Cases +- What happens when URL exceeds maximum length? (TEXT type handles this) +- Concurrent inserts with same checksum? (UNIQUE constraint + application logic) +- Timezone handling for expiration? (Always use UTC internally) diff --git a/ai_coder_2/subtasks/Decomp/001-02.md b/ai_coder_2/subtasks/Decomp/001-02.md new file mode 100644 index 0000000..c8bccc9 --- /dev/null +++ b/ai_coder_2/subtasks/Decomp/001-02.md @@ -0,0 +1,73 @@ +# Subtask: Base62 Encoding/Decoding + +**Parent Task**: Decomp/001 +**Subtask ID**: Decomp/001-02 +**Dependencies**: None (can be implemented in parallel with 001-01) + +## Description +Implement Base62 encoding/decoding for converting numeric IDs to short codes. This is a pure algorithm component with no external dependencies. + +## Requirements +- Convert integer ID to Base62 string (0-9, a-z, A-Z) +- Convert Base62 string back to integer ID +- Support IDs up to 10^12 (10M URLs with buffer) +- Handle leading zeros correctly +- No external dependencies for core logic + +## Technical Specifications + +### Algorithm + +```python +ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" +BASE = 62 + +def encode(num: int) -> str: + """Convert integer to Base62 string.""" + if num == 0: + return ALPHABET[0] + result = [] + while num > 0: + num, remainder = divmod(num, BASE) + result.append(ALPHABET[remainder]) + return ''.join(reversed(result)) + +def decode(short_code: str) -> int: + """Convert Base62 string to integer.""" + result = 0 + for char in short_code: + result = result * BASE + ALPHABET.index(char) + return result +``` + +### Complexity Analysis +- **Time**: O(log₆₂(n)) for both operations +- **Space**: O(log₆₂(n)) for output string + +### Code Length Constraints +- Target: <50 lines (Simplicity First principle) +- Single file module: `base62.py` + +## Acceptance Criteria +- [ ] encode(0) returns "0" +- [ ] encode(12345) returns correct Base62 string +- [ ] decode(encode(12345)) == 12345 for all test values +- [ ] Handles edge cases: 0, negative numbers (raise error), max value +- [ ] Unit tests with 100% coverage +- [ ] No external dependencies (stdlib only) +- [ ] <50 lines of code + +## Notes +- **Why Base62**: URL-safe, compact (~62^8 = 218 trillion combinations with 8 chars) +- **Case sensitivity**: URLs are case-sensitive, which is standard +- **Alternative considered**: Base57 (excluding ambiguous chars like 0/O/l/1) - rejected for simplicity + +## Edge Cases +- Empty string input → raise ValueError +- Invalid characters in input → raise ValueError +- Negative numbers → raise ValueError +- Overflow for very large numbers → Python handles big ints natively + +## Performance +- Encoding/decoding should be <1μs per operation +- No memory allocations in tight loops (use list comprehension) diff --git a/ai_coder_2/subtasks/Decomp/001-03.md b/ai_coder_2/subtasks/Decomp/001-03.md new file mode 100644 index 0000000..8d32f73 --- /dev/null +++ b/ai_coder_2/subtasks/Decomp/001-03.md @@ -0,0 +1,101 @@ +# Subtask: Short Code Generation with Collision Handling + +**Parent Task**: Decomp/001 +**Subtask ID**: Decomp/001-03 +**Dependencies**: Decomp/001-01 (Database Schema), Decomp/001-02 (Base62 Encoding) + +## Description +Implement unique short code generation using database sequence IDs with Base62 encoding. Handle hash collisions gracefully when generating codes from URL hashes. + +## Requirements +- Generate 6-8 character short codes +- Handle collisions gracefully (retry with different encoding) +- Support custom alias validation +- Detect duplicate URLs using checksum +- Ensure uniqueness at scale (10M URLs) + +## Technical Specifications + +### Code Generation Strategies + +#### Strategy 1: Sequential ID-based (Primary) +```python +def generate_short_code(url_id: int) -> str: + """Generate short code from sequential database ID.""" + return base62_encode(url_id) +``` +- **Pros**: Guaranteed unique, simple, collision-free +- **Cons**: Predictable (sequential), requires database roundtrip + +#### Strategy 2: Hash-based with Collision Handling (Fallback) +```python +def generate_from_url_hash(url: str, attempt: int = 0) -> str: + """Generate short code from URL hash with collision handling.""" + # SHA-256 hash + salt for collision resolution + salt = f"_{attempt}" if attempt > 0 else "" + hash_val = hashlib.sha256(f"{url}{salt}".encode()).digest() + # Take first 6 bytes and encode + num = int.from_bytes(hash_val[:6], 'big') + return base62_encode(num)[:8] +``` + +### Collision Handling Logic + +```python +def create_short_code(original_url: str, custom_alias: str = None) -> str: + """Create unique short code with collision handling.""" + + # 1. Check for duplicate URL + checksum = hashlib.sha256(original_url.encode()).hexdigest() + existing = db.query("SELECT short_code FROM urls WHERE checksum = %s", checksum) + if existing: + return existing[0]['short_code'] # Return existing code + + # 2. Handle custom alias + if custom_alias: + if not is_valid_alias(custom_alias): + raise ValueError("Invalid custom alias") + if db.exists("SELECT 1 FROM urls WHERE short_code = %s", custom_alias): + raise ValueError("Alias already taken") + return custom_alias + + # 3. Generate ID-based code (primary strategy) + url_id = db.insert("INSERT INTO urls (original_url, checksum) VALUES (%s, %s) RETURNING id", + original_url, checksum) + return base62_encode(url_id) +``` + +### Custom Alias Validation +```python +def is_valid_alias(alias: str) -> bool: + """Validate custom alias format.""" + return bool(re.match(r'^[a-zA-Z0-9]{4,20}$', alias)) +``` + +## Data Structures +- **checksum**: SHA-256 hash of URL for duplicate detection +- **collision_retry_count**: Track collision attempts for monitoring + +## Acceptance Criteria +- [ ] Generated codes are 6-8 characters +- [ ] No duplicate short codes in database (verified by UNIQUE constraint) +- [ ] Duplicate URLs return existing short code +- [ ] Custom aliases validated for format and uniqueness +- [ ] Collision handling retries up to 3 times with different salts +- [ ] Unit tests cover: normal case, duplicate URL, custom alias, collision + +## Notes +- **Why sequential ID as primary**: Simpler, predictable length, no collisions +- **Hash-based as alternative**: For future distributed generation needs +- **Trade-off**: Sequential IDs are guessable but acceptable for public URLs + +## Edge Cases +- URL longer than database limit → truncate before hashing +- Special characters in custom alias → regex validation +- Database connection failure during insert → retry logic +- Concurrent duplicate URL inserts → UNIQUE constraint + application retry + +## Performance +- Duplicate check: O(1) with checksum index +- Insert: <10ms with proper connection pooling +- Custom alias check: O(1) with short_code index diff --git a/ai_coder_2/subtasks/Decomp/001-04.md b/ai_coder_2/subtasks/Decomp/001-04.md new file mode 100644 index 0000000..62623ee --- /dev/null +++ b/ai_coder_2/subtasks/Decomp/001-04.md @@ -0,0 +1,114 @@ +# Subtask: URL Shortening API (Create Endpoint) + +**Parent Task**: Decomp/001 +**Subtask ID**: Decomp/001-04 +**Dependencies**: Decomp/001-01 (Database), Decomp/001-03 (Code Generation) + +## Description +Implement HTTP API for creating short URLs. This is the main entry point for users to shorten URLs. + +## Requirements +- RESTful POST endpoint for creating short URLs +- Support custom alias parameter +- Return short URL and metadata +- Rate limiting for abuse prevention +- Input validation and error handling +- <200ms response time p95 + +## Technical Specifications + +### API Endpoint + +```http +POST /api/v1/shorten +Content-Type: application/json + +{ + "url": "https://example.com/very/long/url", + "custom_alias": "mylink" // optional +} + +Response 201 Created: +{ + "short_code": "abc123", + "short_url": "https://short.est/abc123", + "original_url": "https://example.com/very/long/url", + "created_at": "2025-02-04T10:30:00Z", + "expires_at": null // or ISO timestamp if set +} + +Errors: +400 Bad Request - Invalid URL or alias +409 Conflict - Custom alias already taken +422 Unprocessable Entity - URL validation failed +429 Too Many Requests - Rate limit exceeded +``` + +### Request Validation + +```python +def validate_shorten_request(data: dict) -> tuple[bool, str | None]: + """Validate request payload.""" + url = data.get('url') + if not url: + return False, "URL is required" + + # URL format validation + try: + result = urlparse(url) + if not all([result.scheme, result.netloc]): + return False, "Invalid URL format" + if result.scheme not in ['http', 'https']: + return False, "Only HTTP/HTTPS URLs allowed" + except Exception: + return False, "Invalid URL format" + + # Custom alias validation + custom_alias = data.get('custom_alias') + if custom_alias and not is_valid_alias(custom_alias): + return False, "Invalid custom alias format" + + return True, None +``` + +### Rate Limiting + +```python +# Redis-based rate limiting +RATE_LIMIT = 10 requests per minute per IP + +def check_rate_limit(identifier: str) -> bool: + """Check if identifier exceeded rate limit.""" + key = f"ratelimit:{identifier}:{datetime.utcnow().strftime('%Y%m%d%H%M')}" + count = redis.incr(key) + redis.expire(key, 60) # 1 minute window + return count <= RATE_LIMIT +``` + +## Acceptance Criteria +- [ ] POST /api/v1/shorten endpoint functional +- [ ] Returns 201 with valid response body +- [ ] Validates URL format (scheme, structure) +- [ ] Validates custom alias format +- [ ] Rate limiting enforced (10 req/min per IP) +- [ ] Error responses with proper status codes +- [ ] <200ms p95 latency (excluding rate limit checks) +- [ ] Unit tests + integration tests + +## Notes +- **Framework**: Use FastAPI or Flask (async preferred) +- **Rate limiting**: Redis for distributed scenarios +- **Logging**: Log all URL creations for analytics +- **Monitoring**: Track response times, error rates + +## Edge Cases +- URL with Unicode characters → punycode encoding +- URL with fragments/hash → preserve in original_url +- Empty request body → 400 error +- Malformed JSON → 400 error +- Database timeout → 503 error + +## Performance Optimization +- Connection pooling for database +- Async I/O for database queries +- Cache frequent URLs in Redis (optional optimization) diff --git a/ai_coder_2/subtasks/Decomp/001-05.md b/ai_coder_2/subtasks/Decomp/001-05.md new file mode 100644 index 0000000..bfd66b2 --- /dev/null +++ b/ai_coder_2/subtasks/Decomp/001-05.md @@ -0,0 +1,159 @@ +# Subtask: URL Redirect Endpoint + +**Parent Task**: Decomp/001 +**Subtask ID**: Decomp/001-05 +**Dependencies**: Decomp/001-01 (Database), Decomp/001-03 (Code Generation) + +## Description +Implement HTTP redirect endpoint that resolves short codes to original URLs. This is the most performance-critical path (<50ms p95). + +## Requirements +- Resolve short code to original URL +- Return HTTP 301 (permanent) or 302 (temporary) redirect +- Check link expiration (TTL) +- Record analytics for each redirect +- Cache hot URLs for performance +- <50ms p95 latency + +## Technical Specifications + +### API Endpoint + +```http +GET /{short_code} + +Response 301 Moved Permanently (or 302): +Location: {original_url} + +Response 404 Not Found: +{ + "error": "Short URL not found or expired" +} + +Response 410 Gone: +{ + "error": "Short URL has expired" +} +``` + +### Redirect Logic + +```python +async def redirect_handler(short_code: str, request): + """Handle redirect requests with caching and analytics.""" + + # 1. Check cache first (Redis) + cache_key = f"url:{short_code}" + cached = await redis.get(cache_key) + if cached: + data = json.loads(cached) + await record_analytics(data['url_id'], request) + return RedirectResponse(data['original_url'], status_code=301) + + # 2. Query database + url_data = await db.fetch_one( + "SELECT id, original_url, expires_at FROM urls WHERE short_code = $1", + short_code + ) + + if not url_data: + raise HTTPException(404, "Short URL not found") + + # 3. Check expiration + if url_data['expires_at'] and url_data['expires_at'] < datetime.utcnow(): + raise HTTPException(410, "Short URL has expired") + + # 4. Cache result (5 minute TTL) + await redis.setex(cache_key, 300, json.dumps({ + 'url_id': url_data['id'], + 'original_url': url_data['original_url'] + })) + + # 5. Record analytics (async, non-blocking) + await record_analytics(url_data['id'], request) + + # 6. Return redirect + return RedirectResponse(url_data['original_url'], status_code=301) +``` + +### Analytics Recording + +```python +async def record_analytics(url_id: int, request): + """Record click analytics asynchronously.""" + try: + user_agent = request.headers.get('user-agent', '') + ip_address = request.client.host + referrer = request.headers.get('referer', '') + + # Queue for batch insert (use message queue or buffer) + await analytics_queue.put({ + 'url_id': url_id, + 'clicked_at': datetime.utcnow(), + 'user_agent': user_agent, + 'ip_address': ip_address, + 'referrer': referrer + }) + except Exception: + # Analytics failure should not break redirect + pass +``` + +### Caching Strategy + +```python +# Redis cache configuration +CACHE_TTL = 300 # 5 minutes +CACHE_WARMUP = True # Pre-populate cache for known hot URLs + +async def warmup_cache(): + """Pre-populate cache for frequently accessed URLs.""" + hot_urls = await db.fetch_all( + """SELECT short_code, original_url, id + FROM urls + WHERE access_count > 100 + ORDER BY access_count DESC + LIMIT 1000""" + ) + for url in hot_urls: + await redis.setex( + f"url:{url['short_code']}", + CACHE_TTL, + json.dumps({'url_id': url['id'], 'original_url': url['original_url']}) + ) +``` + +## Acceptance Criteria +- [ ] GET /{short_code} returns 301/302 redirect +- [ ] Resolves short codes to original URLs +- [ ] Returns 404 for non-existent codes +- [ ] Returns 410 for expired URLs +- [ ] Records analytics for each redirect +- [ ] Cache hit rate >80% for hot URLs +- [ ] <50ms p95 latency (measured with load test) +- [ ] Analytics failure doesn't break redirect + +## Notes +- **301 vs 302**: Use 301 for permanent redirects (allows browser caching) +- **Cache strategy**: LRU eviction, 5-minute TTL balances freshness and performance +- **Analytics decoupling**: Async queue ensures analytics don't block redirect +- **Performance bottleneck**: Database query → cache critical + +## Edge Cases +- Short code with special characters → 404 (validation) +- Expired URL → 410 Gone +- Database timeout → serve from stale cache if available +- Analytics queue full → drop analytics, don't block redirect +- IP address spoofing → log X-Forwarded-For header if present + +## Performance Targets +- Cache hit: <5ms +- Cache miss (DB): <50ms +- Analytics recording: <1ms (async, non-blocking) +- Throughput: 100K requests/second (with caching) + +## Monitoring +- Track cache hit/miss ratio +- Monitor p50/p95/p99 latency +- Alert on latency >100ms +- Track error rates (404, 410) diff --git a/ai_coder_2/subtasks/Decomp/001-06.md b/ai_coder_2/subtasks/Decomp/001-06.md new file mode 100644 index 0000000..270a2c5 --- /dev/null +++ b/ai_coder_2/subtasks/Decomp/001-06.md @@ -0,0 +1,127 @@ +# Subtask: Analytics Recording and Storage + +**Parent Task**: Decomp/001 +**Subtask ID**: Decomp/001-06 +**Dependencies**: Decomp/001-01 (Database Schema) + +## Description +Implement analytics recording system for tracking URL clicks. Must handle high-volume writes (100K req/sec) without blocking redirect requests. + +## Requirements +- Record click data: timestamp, user-agent, IP, referrer +- Batch inserts for performance (not row-by-row) +- Non-blocking operation (async queue) +- Handle geo-location lookup (optional) +- Survive database failures gracefully +- Support analytics queries + +## Technical Specifications + +### Data Collection Architecture + +```python +# Async queue for buffering analytics events +class AnalyticsBuffer: + def __init__(self, max_size=10000, flush_interval=5): + self.buffer = [] + self.max_size = max_size + self.flush_interval = flush_interval # seconds + self.lock = asyncio.Lock() + + async def add(self, event: dict): + """Add event to buffer, flush if full.""" + async with self.lock: + self.buffer.append(event) + if len(self.buffer) >= self.max_size: + await self._flush() + + async def _flush(self): + """Batch insert all buffered events.""" + if not self.buffer: + return + + try: + await db.execute_many( + """INSERT INTO url_analytics (url_id, clicked_at, user_agent, ip_address, referrer) + VALUES ($1, $2, $3, $4, $5)""", + self.buffer + ) + self.buffer.clear() + except Exception as e: + # Log error but don't crash + logger.error(f"Analytics flush failed: {e}") + # Keep buffer to retry later +``` + +### Geo-location Lookup (Optional Enhancement) + +```python +async def enrich_geo_location(event: dict) -> dict: + """Add geo-location data to analytics event.""" + try: + ip = event.get('ip_address') + if not ip or ip in ('127.0.0.1', '::1'): + return event + + # Use MaxMind GeoLite2 or similar + geo_data = await geoip_lookup(ip) + event['country_code'] = geo_data.get('country_code') + event['city'] = geo_data.get('city') + except Exception: + pass # Geo-location failure not critical + + return event +``` + +### Background Worker + +```python +async def analytics_worker(): + """Background task to periodically flush analytics buffer.""" + buffer = AnalyticsBuffer() + + while True: + try: + await asyncio.sleep(buffer.flush_interval) + await buffer.flush() + except Exception as e: + logger.error(f"Analytics worker error: {e}") +``` + +## Acceptance Criteria +- [ ] Analytics events captured for all redirects +- [ ] Batch inserts (not single-row) +- [ ] Non-blocking operation (redirect latency unaffected) +- [ ] Survives database failures (drop events, don't crash) +- [ ] Flush interval: 5 seconds or 10K events +- [ ] Unit tests for buffer overflow and error handling + +## Notes +- **Why async queue**: Decouples redirect latency from analytics write speed +- **Batch size**: 10K events balances memory usage and DB efficiency +- **Flush interval**: 5 seconds limits data loss on failure +- **Trade-off**: Accept data loss on crash vs. synchronous writes (chosen async) + +## Alternative: Message Queue (Scale-up Path) +For 1M+ events/sec, replace in-memory buffer with: +- Redis Streams +- Kafka +- RabbitMQ + +## Edge Cases +- Buffer overflow → flush immediately, drop if still full +- Database connection lost → keep buffering, alert, drop when full +- Malformed user-agent → store as-is, don't validate +- IPv6 addresses → store in INET column (PostgreSQL handles this) +- Private IP ranges → skip geo-location lookup + +## Performance Targets +- Memory usage: <100MB for 10K event buffer +- Flush time: <1 second for 10K batch insert +- Zero impact on redirect latency + +## Monitoring +- Buffer size alerts +- Flush success/failure rate +- Events per second throughput +- Database insert latency diff --git a/ai_coder_2/subtasks/Decomp/001-07.md b/ai_coder_2/subtasks/Decomp/001-07.md new file mode 100644 index 0000000..5a8e308 --- /dev/null +++ b/ai_coder_2/subtasks/Decomp/001-07.md @@ -0,0 +1,130 @@ +# Subtask: QR Code Generation + +**Parent Task**: Decomp/001 +**Subtask ID**: Decomp/001-07 +**Dependencies**: Decomp/001-03 (Code Generation), Decomp/001-04 (Create API) + +## Description +Generate QR codes for short URLs. QR codes should be generated on-demand and cached. + +## Requirements +- Generate QR code image (PNG format) for short URLs +- Support configurable size (default 200x200px) +- Cache generated QR codes +- Serve via dedicated endpoint +- Handle QR code with logo (optional enhancement) + +## Technical Specifications + +### API Endpoint + +```http +GET /api/v1/qr/{short_code}?size=200 + +Response 200 OK: +Content-Type: image/png + + + +Response 404 Not Found: +{ + "error": "Short URL not found" +} +``` + +### QR Code Generation + +```python +import qrcode +from io import BytesIO + +async def generate_qr_code(short_url: str, size: int = 200) -> bytes: + """Generate QR code for URL.""" + + # Validate size parameter + if not 50 <= size <= 1000: + raise ValueError("Size must be between 50 and 1000") + + # Create QR code + qr = qrcode.QRCode( + version=1, + error_correction=qrcode.constants.ERROR_CORRECT_L, + box_size=max(1, size // 25), # Approximate scaling + border=4, + ) + qr.add_data(short_url) + qr.make(fit=True) + + # Generate image + img = qr.make_image(fill_color="black", back_color="white") + + # Resize to exact dimensions + img = img.resize((size, size), resample=0) + + # Convert to bytes + buffer = BytesIO() + img.save(buffer, format='PNG') + return buffer.getvalue() +``` + +### Caching Strategy + +```python +async def get_qr_code(short_code: str, size: int = 200) -> bytes: + """Get QR code from cache or generate new one.""" + + cache_key = f"qr:{short_code}:{size}" + + # Check cache + cached = await redis.get(cache_key) + if cached: + return cached + + # Verify short code exists + url_data = await db.fetch_one( + "SELECT short_code FROM urls WHERE short_code = $1", + short_code + ) + if not url_data: + raise HTTPException(404, "Short URL not found") + + # Generate QR code + short_url = f"{BASE_URL}/{short_code}" + qr_data = await generate_qr_code(short_url, size) + + # Cache for 24 hours + await redis.setex(cache_key, 86400, qr_data) + + return qr_data +``` + +## Acceptance Criteria +- [ ] GET /api/v1/qr/{short_code} returns PNG image +- [ ] QR code scans to correct short URL +- [ ] Size parameter validated (50-1000px) +- [ ] QR codes cached in Redis (24 hour TTL) +- [ ] Returns 404 for non-existent short codes +- [ ] Unit tests for QR generation and caching + +## Notes +- **Library**: `qrcode` (pip install qrcode[pil]) +- **Cache duration**: 24 hours (QR codes don't change) +- **Error correction**: L (7%) for smallest size +- **Trade-off**: Generate on-demand vs. pre-generate (on-demand chosen for flexibility) + +## Edge Cases +- Invalid size parameter → 400 error +- Short URL longer than QR capacity → use higher version QR +- Concurrent generation → use cache lock or accept duplicate work +- QR library failure → 500 error + +## Performance Targets +- Generation time: <100ms +- Cache hit: <10ms (Redis fetch) +- Memory per QR: ~10KB (200x200 PNG) + +## Optional Enhancements +- Logo in center (requires higher error correction) +- Different colors +- Vector format (SVG) for print +- Bulk generation for analytics diff --git a/ai_coder_2/subtasks/Decomp/001-08.md b/ai_coder_2/subtasks/Decomp/001-08.md new file mode 100644 index 0000000..caf26fc --- /dev/null +++ b/ai_coder_2/subtasks/Decomp/001-08.md @@ -0,0 +1,225 @@ +# Subtask: Analytics Query API + +**Parent Task**: Decomp/001 +**Subtask ID**: Decomp/001-08 +**Dependencies**: Decomp/001-01 (Database), Decomp/001-06 (Analytics Recording) + +## Description +Implement API endpoints for querying URL analytics. Provide statistics, click history, and aggregated data. + +## Requirements +- Get click count for a short URL +- Get click history with pagination +- Aggregate analytics by day/country/device +- Support date range filtering +- <500ms response time p95 + +## Technical Specifications + +### API Endpoints + +```http +# Get URL statistics +GET /api/v1/stats/{short_code} + +Response 200 OK: +{ + "short_code": "abc123", + "original_url": "https://example.com", + "created_at": "2025-02-01T10:00:00Z", + "total_clicks": 1234, + "last_clicked": "2025-02-04T15:30:00Z", + "expires_at": null +} + +# Get click history with pagination +GET /api/v1/analytics/{short_code}?page=1&limit=50&start_date=2025-02-01&end_date=2025-02-04 + +Response 200 OK: +{ + "short_code": "abc123", + "total_clicks": 1234, + "page": 1, + "limit": 50, + "total_pages": 25, + "clicks": [ + { + "clicked_at": "2025-02-04T15:30:00Z", + "user_agent": "Mozilla/5.0...", + "country_code": "US", + "city": "San Francisco", + "referrer": "https://google.com" + } + ] +} + +# Get aggregated statistics +GET /api/v1/analytics/{short_code}/aggregate?group_by=day&start_date=2025-02-01 + +Response 200 OK: +{ + "short_code": "abc123", + "aggregation": "day", + "data": [ + {"date": "2025-02-01", "clicks": 150}, + {"date": "2025-02-02", "clicks": 230}, + {"date": "2025-02-03", "clicks": 456}, + {"date": "2025-02-04", "clicks": 398} + ] +} +``` + +### Query Implementation + +```python +async def get_url_stats(short_code: str) -> dict: + """Get basic statistics for a short URL.""" + url_data = await db.fetch_one( + """SELECT short_code, original_url, created_at, expires_at, access_count + FROM urls WHERE short_code = $1""", + short_code + ) + + if not url_data: + raise HTTPException(404, "Short URL not found") + + last_click = await db.fetch_one( + """SELECT clicked_at FROM url_analytics + WHERE url_id = $1 + ORDER BY clicked_at DESC LIMIT 1""", + url_data['id'] + ) + + return { + "short_code": url_data['short_code'], + "original_url": url_data['original_url'], + "created_at": url_data['created_at'].isoformat(), + "total_clicks": url_data['access_count'], + "last_clicked": last_click['clicked_at'].isoformat() if last_click else None, + "expires_at": url_data['expires_at'].isoformat() if url_data['expires_at'] else None + } + +async def get_click_history(short_code: str, page: int = 1, limit: int = 50, + start_date: str = None, end_date: str = None) -> dict: + """Get paginated click history.""" + + # Build query with filters + conditions = ["url_id = (SELECT id FROM urls WHERE short_code = $1)"] + params = [short_code] + param_count = 1 + + if start_date: + param_count += 1 + conditions.append(f"clicked_at >= ${param_count}") + params.append(start_date) + + if end_date: + param_count += 1 + conditions.append(f"clicked_at <= ${param_count}") + params.append(end_date) + + where_clause = " AND ".join(conditions) + + # Get total count + total = await db.fetch_one( + f"SELECT COUNT(*) as count FROM url_analytics WHERE {where_clause}", + *params + ) + total_clicks = total['count'] + total_pages = (total_clicks + limit - 1) // limit + + # Get paginated results + offset = (page - 1) * limit + clicks = await db.fetch_all( + f"""SELECT clicked_at, user_agent, country_code, city, referrer + FROM url_analytics + WHERE {where_clause} + ORDER BY clicked_at DESC + LIMIT ${param_count + 1} OFFSET ${param_count + 2}""", + *params, limit, offset + ) + + return { + "short_code": short_code, + "total_clicks": total_clicks, + "page": page, + "limit": limit, + "total_pages": total_pages, + "clicks": [dict(click) for click in clicks] + } + +async def get_aggregated_clicks(short_code: str, group_by: str = 'day', + start_date: str = None, end_date: str = None) -> dict: + """Get aggregated click statistics.""" + + # Map group_by to SQL date truncation + trunc_map = { + 'day': "DATE_TRUNC('day', clicked_at)", + 'hour': "DATE_TRUNC('hour', clicked_at)", + 'month': "DATE_TRUNC('month', clicked_at)" + } + + if group_by not in trunc_map: + raise HTTPException(400, f"Invalid group_by: {group_by}") + + date_trunc = trunc_map[group_by] + + # Build query + conditions = ["url_id = (SELECT id FROM urls WHERE short_code = $1)"] + params = [short_code] + param_count = 1 + + if start_date: + param_count += 1 + conditions.append(f"clicked_at >= ${param_count}") + params.append(start_date) + + if end_date: + param_count += 1 + conditions.append(f"clicked_at <= ${param_count}") + params.append(end_date) + + where_clause = " AND ".join(conditions) + + query = f""" + SELECT {date_trunc} as period, COUNT(*) as clicks + FROM url_analytics + WHERE {where_clause} + GROUP BY period + ORDER BY period ASC + """ + + results = await db.fetch_all(query, *params) + + return { + "short_code": short_code, + "aggregation": group_by, + "data": [{"date": r['period'].isoformat(), "clicks": r['clicks']} for r in results] + } +``` + +## Acceptance Criteria +- [ ] GET /api/v1/stats/{short_code} returns URL statistics +- [ ] GET /api/v1/analytics/{short_code} returns paginated click history +- [ ] GET /api/v1/analytics/{short_code}/aggregate returns aggregated data +- [ ] Date range filtering works correctly +- [ ] Pagination works correctly (page, limit, total_pages) +- [ ] Group by day/hour/month supported +- [ ] <500ms p95 response time +- [ ] Unit tests for all endpoints + +## Notes +- **Database indexes**: Composite index on (url_id, clicked_at) critical for performance +- **Pagination**: Cursor-based pagination better for large datasets (future enhancement) +- **Caching**: Cache stats endpoint (5 minute TTL) + +## Edge Cases +- URL with no clicks → return 0 total_clicks +- Page beyond total_pages → return empty array +- Invalid date format → 400 error +- Group by not supported → 400 error + +## Performance Optimization +- Materialized view for aggregated stats (if query is slow) +- Query timeout: 5 seconds +- Limit max results: 10,000 per query diff --git a/ai_coder_2/subtasks/Decomp/001-09.md b/ai_coder_2/subtasks/Decomp/001-09.md new file mode 100644 index 0000000..ebe8d2f --- /dev/null +++ b/ai_coder_2/subtasks/Decomp/001-09.md @@ -0,0 +1,182 @@ +# Subtask: Redis Caching Layer + +**Parent Task**: Decomp/001 +**Subtask ID**: Decomp/001-09 +**Dependencies**: None (can be implemented in parallel) + +## Description +Implement Redis caching layer for URL lookups to achieve <50ms p95 latency. Handle cache warming, eviction, and failure scenarios. + +## Requirements +- Cache short URL → original URL mapping +- Cache hit rate >80% +- TTL-based eviction (5 minutes for hot URLs) +- Graceful degradation on Redis failure +- Connection pooling and retry logic + +## Technical Specifications + +### Cache Configuration + +```python +import redis.asyncio as redis +from typing import Optional + +class URLCache: + def __init__(self, redis_url: str = "redis://localhost:6379"): + self.pool = redis.ConnectionPool.from_url( + redis_url, + max_connections=50, + retry_on_timeout=True, + retry_on_error=[redis.ConnectionError, redis.TimeoutError], + socket_timeout=2, + socket_connect_timeout=2 + ) + self.redis = redis.Redis(connection_pool=self.pool) + self.default_ttl = 300 # 5 minutes + + async def get_url(self, short_code: str) -> Optional[dict]: + """Get URL from cache.""" + try: + data = await self.redis.get(f"url:{short_code}") + return json.loads(data) if data else None + except Exception as e: + logger.warning(f"Cache get failed: {e}") + return None # Degrade gracefully + + async def set_url(self, short_code: str, url_data: dict, ttl: int = None): + """Set URL in cache.""" + try: + ttl = ttl or self.default_ttl + await self.redis.setex( + f"url:{short_code}", + ttl, + json.dumps(url_data) + ) + except Exception as e: + logger.warning(f"Cache set failed: {e}") + # Don't raise, cache failure is non-critical + + async def invalidate(self, short_code: str): + """Invalidate cache entry.""" + try: + await self.redis.delete(f"url:{short_code}") + except Exception as e: + logger.warning(f"Cache invalidation failed: {e}") + + async def get_multi(self, short_codes: list[str]) -> dict[str, dict]: + """Batch get multiple URLs from cache.""" + try: + keys = [f"url:{code}" for code in short_codes] + values = await self.redis.mget(keys) + return { + code: json.loads(v) + for code, v in zip(short_codes, values) + if v is not None + } + except Exception as e: + logger.warning(f"Batch cache get failed: {e}") + return {} + + async def close(self): + """Close connections.""" + await self.redis.close() + await self.pool.disconnect() +``` + +### Cache Warming Strategy + +```python +async def warmup_cache(cache: URLCache, db): + """Pre-populate cache with hot URLs.""" + + # Get top 1000 URLs by access count + hot_urls = await db.fetch_all(""" + SELECT id, short_code, original_url, access_count + FROM urls + WHERE access_count > 10 + ORDER BY access_count DESC + LIMIT 1000 + """) + + # Pipeline for faster bulk loading + pipe = cache.redis.pipeline() + + for url in hot_urls: + key = f"url:{url['short_code']}" + data = json.dumps({ + 'url_id': url['id'], + 'original_url': url['original_url'] + }) + pipe.setex(key, cache.default_ttl, data) + + await pipe.execute() + logger.info(f"Warmed up cache with {len(hot_urls)} URLs") +``` + +### Cache-Aside Pattern Integration + +```python +async def get_url_with_cache(short_code: str, cache: URLCache, db): + """Get URL using cache-aside pattern.""" + + # 1. Try cache first + cached = await cache.get_url(short_code) + if cached: + return cached['original_url'], True # True = cache hit + + # 2. Cache miss: query database + url_data = await db.fetch_one( + "SELECT id, original_url, expires_at FROM urls WHERE short_code = $1", + short_code + ) + + if not url_data: + return None, False + + # Check expiration + if url_data['expires_at'] and url_data['expires_at'] < datetime.utcnow(): + return None, False + + # 3. Populate cache for next request + await cache.set_url(short_code, { + 'url_id': url_data['id'], + 'original_url': url_data['original_url'] + }) + + return url_data['original_url'], False # False = cache miss +``` + +## Acceptance Criteria +- [ ] URLCache class implemented with async methods +- [ ] Cache hit rate >80% for hot URLs +- [ ] Graceful degradation on Redis failure (return None, don't crash) +- [ ] Connection pooling configured (max 50 connections) +- [ ] Cache warming function implemented +- [ ] TTL properly configured (5 minutes default) +- [ ] Unit tests for cache hit/miss scenarios + +## Notes +- **Why Redis**: Fast in-memory store, supports TTL, distributed +- **Cache-aside**: Simple pattern, avoids stale data issues +- **Graceful degradation**: System works even if Redis is down +- **Trade-off**: Accept stale data for 5 minutes vs. cache invalidation overhead + +## Failure Scenarios +- Redis connection lost → return cache miss, query DB +- Redis timeout → log warning, continue without cache +- OOM error → Redis evicts oldest keys (LRU), acceptable +- Network partition → continue without cache + +## Performance Targets +- Cache GET: <5ms p95 +- Cache SET: <10ms p95 +- Batch GET (100 keys): <50ms p95 +- Memory usage: <1GB for 100K cached URLs + +## Monitoring +- Cache hit/miss ratio (target >80%) +- Redis connection errors +- Memory usage +- Eviction rate +- Command execution times diff --git a/ai_coder_2/subtasks/Decomp/001-10.md b/ai_coder_2/subtasks/Decomp/001-10.md new file mode 100644 index 0000000..7c11d1b --- /dev/null +++ b/ai_coder_2/subtasks/Decomp/001-10.md @@ -0,0 +1,196 @@ +# Subtask: Rate Limiting Implementation + +**Parent Task**: Decomp/001 +**Subtask ID**: Decomp/001-10 +**Dependencies**: Decomp/001-09 (Redis Cache) - uses Redis for distributed rate limiting + +## Description +Implement rate limiting to prevent abuse of the URL shortening service. Support different limits for different actions (create vs. redirect). + +## Requirements +- Rate limit URL creation (10 per minute per IP) +- Rate limit redirects (100 per second per IP) +- Support API key-based rate limiting (higher limits) +- Distributed (works across multiple instances) +- Sliding window algorithm +- Return proper HTTP headers (X-RateLimit-*) + +## Technical Specifications + +### Rate Limiting Configuration + +```python +from dataclasses import dataclass +from enum import Enum + +class Action(Enum): + CREATE = "create" + REDIRECT = "redirect" + +@dataclass +class RateLimit: + requests: int + window: int # seconds + +RATE_LIMITS = { + Action.CREATE: RateLimit(requests=10, window=60), # 10/min + Action.REDIRECT: RateLimit(requests=100, window=1), # 100/sec +} + +API_KEY_LIMITS = { + Action.CREATE: RateLimit(requests=100, window=60), # 100/min + Action.REDIRECT: RateLimit(requests=1000, window=1), # 1000/sec +} +``` + +### Sliding Window Implementation + +```python +class RateLimiter: + def __init__(self, redis: redis.Redis): + self.redis = redis + + async def check_rate_limit( + self, + identifier: str, # IP address or API key + action: Action, + api_key: str = None + ) -> tuple[bool, dict]: + """ + Check if request is within rate limit. + Returns (allowed, rate_limit_info) + """ + + # Get limits + limits = API_KEY_LIMITS if api_key else RATE_LIMITS + limit = limits[action] + + # Sliding window key + key = f"ratelimit:{action.value}:{identifier}" + now = time.time() + window_start = now - limit.window + + # Clean up old entries and count current window + pipe = self.redis.pipeline() + pipe.zremrangebyscore(key, 0, window_start) + pipe.zcard(key) + pipe.zadd(key, {str(now): now}) + pipe.expire(key, limit.window) + results = await pipe.execute() + + current_count = results[1] + remaining = max(0, limit.requests - current_count - 1) + reset_at = now + limit.window + + allowed = current_count < limit.requests + + return allowed, { + "limit": limit.requests, + "remaining": remaining, + "reset": int(reset_at) + } + + async def is_allowed(self, identifier: str, action: Action, api_key: str = None) -> bool: + """Simple check without returning info.""" + allowed, _ = await self.check_rate_limit(identifier, action, api_key) + return allowed +``` + +### Middleware Integration + +```python +from fastapi import Request, HTTPException +from fastapi.responses import JSONResponse + +async def rate_limit_middleware(request: Request, call_next): + """Rate limiting middleware.""" + + # Extract identifier + api_key = request.headers.get("X-API-Key") + identifier = api_key or request.client.host + + # Determine action based on path + if request.url.path == "/api/v1/shorten" and request.method == "POST": + action = Action.CREATE + elif request.url.path.startswith("/api/v1/"): + action = Action.REDIRECT # Analytics, stats, etc. + else: + # Redirect paths (/{short_code}) - no rate limiting + return await call_next(request) + + # Check rate limit + limiter = request.app.state.rate_limiter + allowed, info = await limiter.check_rate_limit(identifier, action, api_key) + + # Add rate limit headers + headers = { + "X-RateLimit-Limit": str(info["limit"]), + "X-RateLimit-Remaining": str(info["remaining"]), + "X-RateLimit-Reset": str(info["reset"]) + } + + if not allowed: + return JSONResponse( + status_code=429, + content={"error": "Rate limit exceeded", "retry_after": info["reset"]}, + headers=headers + ) + + response = await call_next(request) + response.headers.update(headers) + return response +``` + +### Request Extraction Helper + +```python +def extract_identifier(request: Request) -> tuple[str, str | None]: + """ + Extract rate limit identifier from request. + Returns (identifier, api_key) + """ + # Check for API key first + api_key = request.headers.get("X-API-Key") + if api_key: + return api_key, api_key + + # Fall back to IP address + # Check for forwarded headers (behind proxy) + forwarded_for = request.headers.get("X-Forwarded-For") + if forwarded_for: + return forwarded_for.split(",")[0].strip(), None + + return request.client.host, None +``` + +## Acceptance Criteria +- [ ] RateLimiter class with sliding window algorithm +- [ ] CREATE action limited to 10/min per IP (100/min with API key) +- [ ] REDIRECT action limited to 100/sec per IP (1000/sec with API key) +- [ ] X-RateLimit-* headers returned on all responses +- [ ] 429 status code when limit exceeded +- [ ] Works across multiple instances (Redis-backed) +- [ ] Unit tests for rate limit logic + +## Notes +- **Why sliding window**: More accurate than fixed window, simpler than token bucket +- **Why Redis sorted sets**: Efficient for time-series data, ZREM range for cleanup +- **API key support**: Allows premium users higher limits +- **Trade-off**: Exact vs. approximate (sliding window is exact but more expensive) + +## Edge Cases +- Clock skew → use Redis time, not client time +- Distributed systems → Redis provides single source of truth +- Burst traffic → sliding window handles better than fixed window +- API key leaking → consider adding HMAC signature + +## Alternative Algorithms +- **Token Bucket**: Allows burst, more complex +- **Fixed Window**: Simpler but allows double requests at boundary +- **Leaky Bucket**: Smooths traffic, harder to implement + +## Monitoring +- Rate limit hit rate (percentage of requests limited) +- API key usage distribution +- Top offenders by IP +- Redis sorted set size diff --git a/ai_coder_2/subtasks/Decomp/001-11.md b/ai_coder_2/subtasks/Decomp/001-11.md new file mode 100644 index 0000000..13f9011 --- /dev/null +++ b/ai_coder_2/subtasks/Decomp/001-11.md @@ -0,0 +1,215 @@ +# Subtask: Background Jobs and Cleanup + +**Parent Task**: Decomp/001 +**Subtask ID**: Decomp/001-11 +**Dependencies**: Decomp/001-01 (Database), Decomp/001-06 (Analytics) + +## Description +Implement background job system for periodic tasks: expired URL cleanup, analytics aggregation, cache warming, and maintenance tasks. + +## Requirements +- Clean up expired URLs periodically +- Archive old analytics data +- Warm up cache with hot URLs +- Database maintenance (VACUUM, ANALYZE) +- Job scheduling and monitoring + +## Technical Specifications + +### Job Framework + +```python +import asyncio +from datetime import datetime, timedelta +from typing import Callable + +class JobScheduler: + def __init__(self): + self.jobs = [] + self.running = False + + def schedule(self, interval: int, job: Callable, name: str): + """Schedule a periodic job.""" + self.jobs.append({ + 'name': name, + 'interval': interval, + 'job': job, + 'last_run': None + }) + + async def start(self): + """Start all scheduled jobs.""" + self.running = True + tasks = [asyncio.create_task(self._run_job(job)) for job in self.jobs] + await asyncio.gather(*tasks) + + async def _run_job(self, job_config: dict): + """Run a single job periodically.""" + while self.running: + try: + await job_config['job']() + job_config['last_run'] = datetime.utcnow() + await asyncio.sleep(job_config['interval']) + except Exception as e: + logger.error(f"Job {job_config['name']} failed: {e}") + await asyncio.sleep(60) # Wait before retry + + async def stop(self): + """Stop all jobs.""" + self.running = False +``` + +### Expired URL Cleanup + +```python +async def cleanup_expired_urls(): + """Delete expired URLs and their analytics.""" + deleted_count = await db.execute(""" + DELETE FROM urls + WHERE expires_at IS NOT NULL + AND expires_at < NOW() + RETURNING id + """) + + if deleted_count > 0: + logger.info(f"Cleaned up {deleted_count} expired URLs") + + # Note: Analytics are deleted via ON DELETE CASCADE +``` + +### Analytics Data Archival + +```python +async def archive_old_analytics(): + """ + Archive analytics older than 90 days to separate table or cold storage. + For simplicity, we'll move to an archive table. + """ + + cutoff_date = datetime.utcnow() - timedelta(days=90) + + # Create archive table if not exists + await db.execute(""" + CREATE TABLE IF NOT EXISTS url_analytics_archive ( + LIKE url_analytics INCLUDING ALL + ) + """) + + # Move old data to archive + moved_count = await db.execute(""" + WITH archived AS ( + DELETE FROM url_analytics + WHERE clicked_at < $1 + RETURNING * + ) + INSERT INTO url_analytics_archive + SELECT * FROM archived + RETURNING * + """, cutoff_date) + + if moved_count > 0: + logger.info(f"Archived {moved_count} old analytics records") + + # Optional: VACUUM to reclaim space + await db.execute("VACUUM ANALYZE url_analytics") +``` + +### Cache Warming Job + +```python +async def periodic_cache_warmup(): + """Periodically warm up cache with hot URLs.""" + try: + await warmup_cache(cache, db) + logger.info("Cache warmup completed") + except Exception as e: + logger.error(f"Cache warmup failed: {e}") +``` + +### Database Maintenance + +```python +async def database_maintenance(): + """Run periodic database maintenance.""" + try: + # Update statistics for query planner + await db.execute("ANALYZE urls") + await db.execute("ANALYZE url_analytics") + + # Clean up dead tuples (VACUUM) + await db.execute("VACUUM ANALYZE") + + logger.info("Database maintenance completed") + except Exception as e: + logger.error(f"Database maintenance failed: {e}") +``` + +### Job Scheduling Configuration + +```python +def setup_scheduler(scheduler: JobScheduler): + """Configure all scheduled jobs.""" + + # Expired URL cleanup - every hour + scheduler.schedule( + interval=3600, + job=cleanup_expired_urls, + name="cleanup_expired_urls" + ) + + # Analytics archival - daily at 2 AM + scheduler.schedule( + interval=86400, # 24 hours + job=archive_old_analytics, + name="archive_old_analytics" + ) + + # Cache warmup - every 10 minutes + scheduler.schedule( + interval=600, + job=periodic_cache_warmup, + name="cache_warmup" + ) + + # Database maintenance - weekly + scheduler.schedule( + interval=604800, # 7 days + job=database_maintenance, + name="database_maintenance" + ) +``` + +## Acceptance Criteria +- [ ] JobScheduler class implemented +- [ ] Expired URLs cleaned up hourly +- [ ] Old analytics (>90 days) archived daily +- [ ] Cache warmed up every 10 minutes +- [ ] Database maintenance runs weekly +- [ ] Jobs handle failures gracefully (retry after 60 seconds) +- [ ] Logging for job execution and failures +- [ ] Unit tests for each job function + +## Notes +- **Why async jobs**: Non-blocking, can run alongside API server +- **Why CASCADE delete**: Analytics auto-delete when URL deleted +- **Archive strategy**: Separate table for cold data (can be moved to S3 later) +- **VACUUM timing**: Run during low traffic (weekly) + +## Edge Cases +- Database connection lost → retry after delay +- VACUUM locks table → run during maintenance window +- Archive table doesn't exist → create on first run +- Large data volume → batch deletes (1000 at a time) + +## Alternative: External Job Scheduler +For production, consider: +- **Celery Beat**: More robust, distributed +- **Kubernetes CronJob**: Container-native +- **AWS EventBridge**: Cloud-native +- **cron**: Simple but no monitoring + +## Monitoring +- Job execution timestamps +- Job failure rates +- Records affected per job +- Job duration (alert if >5 minutes) diff --git a/ai_coder_2/subtasks/Decomp/001-12.md b/ai_coder_2/subtasks/Decomp/001-12.md new file mode 100644 index 0000000..fb07a20 --- /dev/null +++ b/ai_coder_2/subtasks/Decomp/001-12.md @@ -0,0 +1,276 @@ +# Subtask: Health Check and Monitoring + +**Parent Task**: Decomp/001 +**Subtask ID**: Decomp/001-12 +**Dependencies**: All previous subtasks + +## Description +Implement health check endpoints and monitoring for the service. Support readiness/liveness probes, dependency health checks, and metrics collection. + +## Requirements +- Health check endpoint (/health) +- Readiness check (database, redis connectivity) +- Liveness check (basic service status) +- Metrics endpoint (Prometheus format) +- Dependency health monitoring + +## Technical Specifications + +### Health Check Endpoints + +```http +# Liveness probe - is the service running? +GET /health/live + +Response 200 OK: +{"status": "alive"} + +# Readiness probe - is the service ready to serve traffic? +GET /health/ready + +Response 200 OK: +{ + "status": "ready", + "checks": { + "database": "ok", + "redis": "ok", + "analytics_queue": "ok" + } +} + +Response 503 Service Unavailable: +{ + "status": "not_ready", + "checks": { + "database": "failed", + "redis": "ok", + "analytics_queue": "ok" + }, + "failed_checks": ["database"] +} + +# Detailed health with metrics +GET /health + +Response 200 OK: +{ + "status": "healthy", + "version": "1.0.0", + "uptime_seconds": 3600, + "checks": { + "database": {"status": "ok", "latency_ms": 5}, + "redis": {"status": "ok", "latency_ms": 2}, + "analytics_queue": {"status": "ok", "queue_size": 123} + }, + "metrics": { + "total_urls": 1234567, + "total_clicks": 98765432, + "cache_hit_rate": 0.87, + "active_connections": 42 + } +} +``` + +### Health Check Implementation + +```python +from datetime import datetime +from time import time + +class HealthChecker: + def __init__(self, db, redis, analytics_queue): + self.db = db + self.redis = redis + self.analytics_queue = analytics_queue + self.start_time = time() + + async def check_liveness(self) -> dict: + """Basic liveness check.""" + return {"status": "alive"} + + async def check_readiness(self) -> dict: + """Check if all dependencies are ready.""" + checks = {} + failed = [] + + # Database check + try: + start = time() + await self.db.fetch_one("SELECT 1") + checks["database"] = "ok" + except Exception as e: + checks["database"] = f"failed: {str(e)}" + failed.append("database") + + # Redis check + try: + start = time() + await self.redis.ping() + checks["redis"] = "ok" + except Exception as e: + checks["redis"] = f"failed: {str(e)}" + failed.append("redis") + + # Analytics queue check + try: + queue_size = await self.analytics_queue.qsize() + checks["analytics_queue"] = "ok" + except Exception as e: + checks["analytics_queue"] = f"failed: {str(e)}" + failed.append("analytics_queue") + + if failed: + return { + "status": "not_ready", + "checks": checks, + "failed_checks": failed + } + + return { + "status": "ready", + "checks": checks + } + + async def check_detailed(self) -> dict: + """Detailed health check with metrics.""" + checks = {} + metrics = {} + + # Database health with latency + try: + start = time() + await self.db.fetch_one("SELECT 1") + db_latency = (time() - start) * 1000 + + # Get some metrics + url_count = await self.db.fetch_one("SELECT COUNT(*) as count FROM urls") + click_count = await self.db.fetch_one("SELECT SUM(access_count) as count FROM urls") + + checks["database"] = {"status": "ok", "latency_ms": round(db_latency, 2)} + metrics["total_urls"] = url_count['count'] + metrics["total_clicks"] = click_count['count'] or 0 + except Exception as e: + checks["database"] = {"status": "failed", "error": str(e)} + + # Redis health with latency + try: + start = time() + await self.redis.ping() + redis_latency = (time() - start) * 1000 + + # Get cache info + info = await self.redis.info('stats') + hit_rate = info.get('keyspace_hits', 0) / max(1, info.get('keyspace_hits', 0) + info.get('keyspace_misses', 0)) + + checks["redis"] = {"status": "ok", "latency_ms": round(redis_latency, 2)} + metrics["cache_hit_rate"] = round(hit_rate, 3) + except Exception as e: + checks["redis"] = {"status": "failed", "error": str(e)} + + # Analytics queue + try: + queue_size = await self.analytics_queue.qsize() + checks["analytics_queue"] = {"status": "ok", "queue_size": queue_size} + except Exception as e: + checks["analytics_queue"] = {"status": "failed", "error": str(e)} + + uptime = time() - self.start_time + + return { + "status": "healthy" if all(c.get("status") == "ok" for c in checks.values()) else "degraded", + "version": os.getenv("APP_VERSION", "1.0.0"), + "uptime_seconds": round(uptime, 2), + "checks": checks, + "metrics": metrics + } +``` + +### Prometheus Metrics Endpoint + +```http +GET /metrics + +Response 200 OK (text/plain): +# HELP url_shortener_urls_total Total number of URLs +# TYPE url_shortener_urls_total gauge +url_shortener_urls_total 1234567 + +# HELP url_shortener_clicks_total Total number of clicks +# TYPE url_shortener_clicks_total gauge +url_shortener_clicks_total 98765432 + +# HELP url_shortener_cache_hits Cache hits +# TYPE url_shortener_cache_hits counter +url_shortener_cache_hits 87654321 + +# HELP url_shortener_cache_misses Cache misses +# TYPE url_shortener_cache_misses counter +url_shortener_cache_misses 12345678 + +# HELP url_shortener_request_latency_seconds Request latency +# TYPE url_shortener_request_latency_seconds histogram +url_shortener_request_latency_seconds_bucket{le="0.005"} 12345 +url_shortener_request_latency_seconds_bucket{le="0.01"} 23456 +... +url_shortener_request_latency_seconds_bucket{le="+Inf"} 99999 +url_shortener_request_latency_seconds_sum 456.78 +url_shortener_request_latency_seconds_count 99999 + +# HELP url_shortener_rate_limit_exceeded Rate limit exceeded +# TYPE url_shortener_rate_limit_exceeded counter +url_shortener_rate_limit_exceeded 1234 +``` + +### Metrics Implementation + +```python +from prometheus_client import Counter, Histogram, Gauge, generate_latest + +# Define metrics +url_count = Gauge('url_shortener_urls_total', 'Total number of URLs') +click_count = Gauge('url_shortener_clicks_total', 'Total number of clicks') +cache_hits = Counter('url_shortener_cache_hits', 'Cache hits') +cache_misses = Counter('url_shortener_cache_misses', 'Cache misses') +request_latency = Histogram('url_shortener_request_latency_seconds', 'Request latency') +rate_limit_exceeded = Counter('url_shortener_rate_limit_exceeded', 'Rate limit exceeded') + +async def metrics_handler(): + """Prometheus metrics endpoint.""" + # Update gauges from database + urls = await db.fetch_one("SELECT COUNT(*) as count FROM urls") + url_count.set(urls['count']) + + clicks = await db.fetch_one("SELECT SUM(access_count) as count FROM urls") + click_count.set(clicks['count'] or 0) + + return Response(content=generate_latest(), media_type="text/plain") +``` + +## Acceptance Criteria +- [ ] GET /health/live returns 200 with {"status": "alive"} +- [ ] GET /health/ready returns 200 when all dependencies OK, 503 otherwise +- [ ] GET /health returns detailed status with metrics +- [ ] GET /metrics returns Prometheus format metrics +- [ ] Health checks have <100ms timeout for each dependency +- [ ] Liveness check always succeeds (no external dependencies) +- [ ] Readiness check fails fast on dependency issues + +## Notes +- **Kubernetes probes**: Use /health/live for liveness, /health/ready for readiness +- **Timeout**: Each health check should timeout within 100ms +- **Circuit breaker**: Mark service unhealthy after 3 consecutive failures +- **Metrics**: Use prometheus_client for standard metrics + +## Edge Cases +- Database timeout → mark as failed, don't block +- Redis down → continue serving (with degraded performance) +- High queue size → alert but don't fail readiness +- Partial metrics available → return what's available + +## Monitoring Checklist +- Uptime (should be 99.9%+) +- Response times (p50, p95, p99) +- Error rates (4xx, 5xx) +- Cache hit rate (>80% target) +- Queue sizes +- Database connection pool usage diff --git a/ai_coder_2/tasks.json b/ai_coder_2/tasks.json new file mode 100644 index 0000000..02f0827 --- /dev/null +++ b/ai_coder_2/tasks.json @@ -0,0 +1,172 @@ +{ + "tasks": [ + { + "task_id": "Decomp/001", + "title": "URL Shortener Service (bit.ly clone)", + "difficulty": "Hard", + "description": "Design a production-ready URL shortener service like bit.ly or tinyurl.com", + "requirements": [ + "Generate short codes (6-8 characters) from long URLs", + "Handle redirects with HTTP 301/302", + "Custom alias support (users can choose their short code)", + "QR code generation for short URLs", + "Link expiration with TTL", + "Analytics: click count, timestamp, user-agent, geo-location" + ], + "non_functional": [ + "10M URLs in database", + "100K requests/second throughput", + "99.9% availability", + "<50ms p95 latency for redirects", + "Handle duplicate URL detection" + ], + "constraints": [ + "Base62 encoding for short codes", + "No external dependencies for core logic", + "Must handle hash collisions gracefully" + ], + "considerations": [ + "How to generate unique short codes at scale?", + "How to handle hash collisions?", + "Database schema design (SQL vs NoSQL)?", + "Caching strategy (Redis)?", + "Rate limiting for abuse prevention?" + ] + }, + { + "task_id": "Decomp/002", + "title": "Real-Time Chat Service (Discord/Slack clone)", + "difficulty": "Hard", + "description": "Design a real-time messaging platform supporting multiple channels and online presence", + "requirements": [ + "Real-time message delivery using WebSockets", + "Multiple channels/servers per user", + "Message history with pagination", + "User online/offline status", + "Direct messages (DM) between users", + "Message reactions and emojis", + "File attachments (images, documents)", + "Message search functionality" + ], + "non_functional": [ + "100K concurrent connections", + "<100ms message delivery latency", + "99.95% availability", + "Persistent message storage" + ], + "constraints": [ + "Message ordering must be preserved", + "Handle network reconnection gracefully", + "Support both WebSocket and HTTP fallback" + ], + "considerations": [ + "Message broker choice (Kafka vs RabbitMQ)?", + "How to handle user presence across devices?", + "Message storage optimization (hot vs cold data)?", + "Scaling WebSocket connections?" + ] + }, + { + "task_id": "Decomp/003", + "title": "Distributed Task Queue (Celery/RQ clone)", + "difficulty": "Hard", + "description": "Build a distributed task execution system with worker pools and result storage", + "requirements": [ + "Task scheduling with priorities", + "Retrying failed tasks with exponential backoff", + "Task chaining and workflows (DAG)", + "Periodic/cron-like tasks", + "Task result storage and retrieval", + "Worker health monitoring and auto-recovery", + "Task cancellation support", + "Rate limiting per task type" + ], + "non_functional": [ + "1M tasks/day throughput", + "Horizontal scaling of workers", + "Fault tolerance (broker/worker failures)", + "<1s task scheduling latency" + ], + "constraints": [ + "At-least-once delivery semantics", + "No duplicate task execution", + "Support both sync and async task execution" + ], + "considerations": [ + "Message broker choice (Redis vs RabbitMQ vs Kafka)?", + "Task serialization format?", + "How to handle long-running tasks?", + "Worker scaling strategy?", + "Dead letter queue handling?" + ] + }, + { + "task_id": "Decomp/004", + "title": "E-Commerce Order Processing System", + "difficulty": "Hard", + "description": "Design a robust order processing pipeline handling inventory, payments, and fulfillment", + "requirements": [ + "Shopping cart management", + "Inventory reservation and locking", + "Payment integration (multiple providers)", + "Order status workflow (pending\u2192paid\u2192shipped\u2192delivered)", + "Shipping label generation", + "Order cancellation and refund handling", + "Notification system (email/SMS)", + "Order history and analytics" + ], + "non_functional": [ + "Handle 10K orders/minute peak", + "Exactly-once inventory deduction", + "Payment transaction consistency", + "<200ms checkout flow latency" + ], + "constraints": [ + "ACID properties for order-inventory operations", + "Idempotent payment processing", + "Handle payment failures gracefully" + ], + "considerations": [ + "How to prevent race conditions in inventory?", + "Distributed transaction pattern (Saga vs 2PC)?", + "Payment provider fallback strategy?", + "Order event sourcing for audit trail?" + ] + }, + { + "task_id": "Decomp/005", + "title": "Distributed File Storage System (S3 clone)", + "difficulty": "Hard", + "description": "Design a scalable object storage service with durability and availability guarantees", + "requirements": [ + "File upload/download with chunking", + "Bucket-based organization", + "Access control (ACLs, presigned URLs)", + "File versioning", + "Multi-part upload for large files", + "Automatic replication across nodes", + "Data integrity verification (checksums)", + "Lifecycle policies (expiration, archival)" + ], + "non_functional": [ + "99.999999999% durability (11 9's)", + "99.99% availability", + "Petabyte-scale storage", + "Unlimited file size support", + "<100ms upload latency p95" + ], + "constraints": [ + "Eventually consistent metadata", + "Strong consistency for reads-after-writes", + "No single point of failure" + ], + "considerations": [ + "Erasure coding vs replication?", + "Consistent hashing for data distribution?", + "How to handle node failures?", + "Metadata database design?", + "Storage backend (local filesystem vs object storage)?" + ] + } + ] +} \ No newline at end of file diff --git a/ai_judge/.DS_Store b/ai_judge/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..fbb18b89147aa34cb1ba6220ea6459e0b9f99fb8 GIT binary patch literal 6148 zcmeHKu};G<5IvVlO$9>-21b7YQU&ax3Ke@-253_OQlmta4hWF)8+-y^(w&{ZK+L@J zIc-8x1PemwPO_hKdA46(tT-kjGg!oZq8FlyU znxr+hCjO!W{O&rmPZOHa1(n`kl6kpjbw-j#(Rh}QaVI!>9WD=_md8!3_#3S3idRc9 z8?Qs?nM2PFT~kK4G?(>MFzB?-DC@a;0kgHWXcr%(b?!nN@u}v4%RJ4yXe^b^v=eN3boZwK|{ "ai_coder_1's Subtask 3 excellently specifies 'use Redis with LRU eviction and 1-hour TTL' (concrete), while ai_coder_2 only says 'implement caching' (ambiguous)." + +### Bad vague feedback: +> "ai_coder_1 had better specifications." (What was better? Be specific!) diff --git a/api_client.py b/api_client.py new file mode 100644 index 0000000..1f9581c --- /dev/null +++ b/api_client.py @@ -0,0 +1,209 @@ +# api_client.py +import asyncio +import logging +from contextlib import asynccontextmanager +from typing import Any, Optional +from urllib.parse import urlparse + +import aiohttp +from aiohttp import ClientError, ClientResponseError +from aiolimiter import AsyncLimiter + +logger = logging.getLogger(__name__) + + +class APIClientError(Exception): + """Base exception for API client errors.""" + +class MaxRetriesExceededError(APIClientError): + """Raised when max retries are exceeded.""" + + +class APIClient: + """ + Async HTTP client with retry, rate limiting, and logging. + + Features: + - Reusable TCP connections via persistent session + - Token bucket rate limiting (aiolimiter) + - Exponential backoff with full jitter + - Retry for 5xx, 429, and network errors + - Structured logging + - URL validation + """ + + # Retryable status codes + RETRYABLE_STATUSES = {429, 500, 502, 503, 504} + + def __init__( + self, + base_url: str, + max_retries: int = 3, + rate_limit: int = 10, # requests per second + base_delay: float = 1.0, # seconds + max_delay: float = 60.0, # seconds + timeout: float = 30.0, + ): + """ + :param base_url: API base URL (e.g., 'https://api.example.com') + :param max_retries: Maximum retry attempts + :param rate_limit: Max requests per second + :param base_delay: Initial delay for exponential backoff + :param max_delay: Maximum delay cap + :param timeout: Request timeout in seconds + :raises ValueError: If base_url is invalid + """ + # Validate URL before using it + parsed = urlparse(base_url) + if parsed.scheme not in ("http", "https"): + raise ValueError(f"Invalid URL scheme: {parsed.scheme}. Only http and https are allowed.") + if not parsed.netloc: + raise ValueError(f"Invalid URL: {base_url}. Must include a hostname.") + + self.base_url = base_url.rstrip("/") + self.max_retries = max_retries + self.base_delay = base_delay + self.max_delay = max_delay + self.timeout = aiohttp.ClientTimeout(total=timeout) + + # Rate limiter: token bucket algorithm (thread-safe) + self._limiter = AsyncLimiter(rate_limit, 1.0) + + # Session will be created on first use + self._session: Optional[aiohttp.ClientSession] = None + + async def _get_session(self) -> aiohttp.ClientSession: + """Lazy-initialize and return session.""" + if self._session is None or self._session.closed: + self._session = aiohttp.ClientSession( + timeout=self.timeout, + raise_for_status=False, # We handle errors manually + ) + return self._session + + def _calculate_delay(self, attempt: int) -> float: + """ + Exponential backoff with full jitter. + + delay = base_delay * 2^attempt + Then apply random jitter in [0, delay] + """ + delay = min(self.base_delay * (2 ** attempt), self.max_delay) + import random + return random.uniform(0, delay) + + def _should_retry(self, error: Exception, status: Optional[int]) -> bool: + """Determine if request should be retried.""" + if isinstance(error, (asyncio.TimeoutError, ClientError)): + return True + if status in self.RETRYABLE_STATUSES: + return True + return False + + async def _request( + self, + method: str, + path: str, + **kwargs: Any, + ) -> Any: + """ + Make HTTP request with retry logic. + + :param method: HTTP method (GET, POST, etc.) + :param path: Request path (will be joined with base_url) + :param kwargs: Additional arguments for aiohttp + :return: JSON response + :raises MaxRetriesExceededError: If all retries fail + """ + last_error = None + last_status = None + + for attempt in range(self.max_retries + 1): + # Rate limiting: acquire token before request + await self._limiter.acquire() + + session = await self._get_session() + url = f"{self.base_url}{path}" + + try: + logger.debug(f"Request: {method} {url} (attempt {attempt + 1})") + + async with session.request(method, url, **kwargs) as resp: + last_status = resp.status + + # Success + if 200 <= resp.status < 300: + logger.info(f"Success: {method} {url} -> {resp.status}") + return await resp.json() + + # Build error for retry decision + error = ClientResponseError( + request_info=resp.request_info, + history=resp.history, + status=resp.status, + message=resp.reason or f"HTTP {resp.status}", + ) + + # Check if retryable + if self._should_retry(error, resp.status): + last_error = error + # Only retry if we haven't exhausted attempts + if attempt < self.max_retries: + delay = self._calculate_delay(attempt) + logger.warning( + f"Retryable error: {method} {url} -> {resp.status}. " + f"Retry in {delay:.2f}s" + ) + await asyncio.sleep(delay) + continue + # Last attempt failed - will raise MaxRetriesExceededError below + + # Non-retryable error - raise immediately + if not self._should_retry(error, resp.status): + logger.error(f"Failed: {method} {url} -> {resp.status}") + raise error + + except (asyncio.TimeoutError, ClientError) as e: + last_error = e + if attempt < self.max_retries and self._should_retry(e, None): + delay = self._calculate_delay(attempt) + logger.warning( + f"Network error: {method} {url} -> {type(e).__name__}. " + f"Retry in {delay:.2f}s" + ) + await asyncio.sleep(delay) + continue + raise + + # Should not reach here, but for type safety + raise MaxRetriesExceededError( + f"Max retries exceeded. Last error: {last_error}, status: {last_status}" + ) + + async def get(self, path: str, **kwargs: Any) -> Any: + """GET request.""" + return await self._request("GET", path, **kwargs) + + async def post(self, path: str, **kwargs: Any) -> Any: + """POST request.""" + return await self._request("POST", path, **kwargs) + + async def put(self, path: str, **kwargs: Any) -> Any: + """PUT request.""" + return await self._request("PUT", path, **kwargs) + + async def delete(self, path: str, **kwargs: Any) -> Any: + """DELETE request.""" + return await self._request("DELETE", path, **kwargs) + + async def close(self) -> None: + """Close the session. Call when done using the client.""" + if self._session and not self._session.closed: + await self._session.close() + logger.debug("Client session closed") + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc_val, exc_tb): + await self.close() diff --git a/pytest.ini b/pytest.ini new file mode 100644 index 0000000..6ce6a16 --- /dev/null +++ b/pytest.ini @@ -0,0 +1,24 @@ +[pytest] +# pytest configuration + +# Asyncio mode +asyncio_mode = auto + +# Test discovery patterns +python_files = test_*.py +python_classes = Test* +python_functions = test_* + +# Output options +addopts = + -v + --strict-markers + --tb=short + --cov=api_client + --cov-report=term-missing + --cov-report=html + +# Markers +markers = + slow: marks tests as slow (deselect with '-m "not slow"') + integration: marks tests as integration tests diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..a3c2dd8 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,14 @@ +# HTTP client with retry, rate limiting, and logging +# Core dependencies +aiohttp>=3.9.0 # Async HTTP client +aiolimiter>=1.1.0 # Rate limiting (token bucket) + +# Testing dependencies +pytest>=8.0.0 # Test framework +pytest-asyncio>=0.23.0 # Async test support +pytest-cov>=4.1.0 # Coverage reporting +aioresponses>=0.7.6 # Mock aiohttp responses + +# Development (optional) +ruff>=0.1.0 # Linter & formatter +mypy>=1.8.0 # Type checker diff --git a/tasks.json b/tasks.json new file mode 100644 index 0000000..12d8098 --- /dev/null +++ b/tasks.json @@ -0,0 +1,109 @@ +[ + { + "task_id": "Decomp/001", + "title": "URL Shortener Service (bit.ly clone)", + "description": "Design and implement a production-grade URL shortener service like bit.ly", + "requirements": [ + "Generate short codes (6-8 characters) from long URLs", + "Handle redirects with HTTP 301/302", + "Track click statistics (count, timestamp, user-agent, IP)", + "Rate limiting per user (100 req/min)", + "Expiration dates for URLs", + "Custom aliases for premium users", + "RESTful API interface" + ], + "non_functional": [ + "10M URLs in database", + "100K requests/second throughput", + "<100ms p95 latency for redirects", + "99.9% SLA" + ] + }, + { + "task_id": "Decomp/002", + "title": "Real-time Chat System (Discord/Slack clone)", + "description": "Design and implement a real-time messaging system", + "requirements": [ + "User authentication (JWT-based)", + "Public channels and private direct messages", + "Real-time message delivery (WebSocket)", + "Message persistence and history", + "Online/offline user status", + "Typing indicators", + "File/image uploads", + "Message reactions/emoji" + ], + "non_functional": [ + "100K concurrent connections", + "<50ms message delivery latency", + "1M messages/day storage", + "Horizontal scaling", + "Message ordering guarantees" + ] + }, + { + "task_id": "Decomp/003", + "title": "Distributed Task Queue (Celery clone)", + "description": "Design and implement a distributed task execution system", + "requirements": [ + "Submit tasks (functions) for async execution", + "Task routing to specific worker queues", + "Retry on failure with exponential backoff", + "Task chaining and workflows", + "Scheduled/cron tasks", + "Task result storage", + "Worker health monitoring", + "Priority queues" + ], + "non_functional": [ + "10K tasks/second throughput", + "Worker auto-scaling", + "Fault tolerance (broker/worker failure)", + "At-least-once delivery semantics" + ] + }, + { + "task_id": "Decomp/004", + "title": "E-commerce Order Processing System", + "description": "Design and implement an order processing pipeline for e-commerce", + "requirements": [ + "Product catalog with inventory management", + "Shopping cart with session persistence", + "Order placement with payment integration", + "Order status workflow (pending\u2192paid\u2192shipped\u2192delivered)", + "Inventory reservation on order", + "Payment webhook handling", + "Order cancellation/refund", + "Notification system (email/SMS)" + ], + "non_functional": [ + "Handle flash sales (1000 orders/second)", + "ACID transactions for inventory", + "Payment fraud detection", + "Eventual consistency for order status", + "Audit trail for all changes" + ] + }, + { + "task_id": "Decomp/005", + "title": "File Storage Service with CDN (S3+CloudFront clone)", + "description": "Design and implement a distributed file storage service", + "requirements": [ + "Upload files (multipart for large files)", + "Generate unique identifiers", + "Download files with CDN caching", + "File metadata (name, size, type, checksum)", + "Access control (public/private)", + "Temporary signed URLs", + "File versioning", + "Delete with cleanup" + ], + "non_functional": [ + "Store 1PB of data", + "Handle 100GB files", + "10K uploads/second", + "Global CDN distribution", + "99.99% durability" + ] + } +] \ No newline at end of file diff --git a/test_api_client.py b/test_api_client.py new file mode 100644 index 0000000..87a32d6 --- /dev/null +++ b/test_api_client.py @@ -0,0 +1,351 @@ +# test_api_client.py +""" +Tests for APIClient using aioresponses for HTTP mocking. +No real network requests — all tests are fast and deterministic. +""" + +import asyncio +import re +from unittest.mock import AsyncMock, patch + +import pytest +from aiohttp import ClientError, ClientResponseError +from aioresponses import aioresponses + +from api_client import APIClient, MaxRetriesExceededError + + +@pytest.fixture +async def api_client(): + """Create client instance for testing with cleanup.""" + client = APIClient( + base_url="https://api.test.com", + max_retries=3, + rate_limit=10, + base_delay=0.01, # Fast for tests + ) + yield client + # Cleanup: close session after each test + await client.close() + + +# ==================== URL validation tests ==================== + +def test_valid_url_with_https(): + """Test that valid HTTPS URL is accepted.""" + client = APIClient("https://api.example.com") + assert client.base_url == "https://api.example.com" + + +def test_valid_url_with_http(): + """Test that valid HTTP URL is accepted.""" + client = APIClient("http://api.example.com") + assert client.base_url == "http://api.example.com" + + +def test_trailing_slash_is_stripped(): + """Test that trailing slash is stripped from base_url.""" + client = APIClient("https://api.example.com/") + assert client.base_url == "https://api.example.com" + + +def test_invalid_url_scheme_raises_error(): + """Test that non-http/https schemes raise ValueError.""" + with pytest.raises(ValueError) as exc: + APIClient("ftp://api.example.com") + + assert "Invalid URL scheme" in str(exc.value) + assert "ftp" in str(exc.value) + + +def test_invalid_url_scheme_javascript_raises_error(): + """Test that javascript: URL raises ValueError (security).""" + with pytest.raises(ValueError) as exc: + APIClient("javascript:alert(1)") + + assert "Invalid URL scheme" in str(exc.value) + + +def test_invalid_url_no_hostname_raises_error(): + """Test that URL without hostname raises ValueError.""" + with pytest.raises(ValueError) as exc: + APIClient("not-a-url") + + assert "Invalid URL" in str(exc.value) + + +def test_invalid_url_empty_netloc_raises_error(): + """Test that URL with empty netloc raises ValueError.""" + with pytest.raises(ValueError) as exc: + APIClient("https://") + + assert "Invalid URL" in str(exc.value) + + +@pytest.mark.asyncio +async def test_successful_get_request(api_client): + """Test successful GET request returns JSON.""" + with aioresponses() as m: + m.get("https://api.test.com/users/1", payload={"id": 1, "name": "Test"}) + + result = await api_client.get("/users/1") + + assert result == {"id": 1, "name": "Test"} + + +@pytest.mark.asyncio +async def test_successful_post_request(api_client): + """Test successful POST request.""" + with aioresponses() as m: + m.post( + "https://api.test.com/users", + payload={"id": 2, "created": True}, + status=201, + ) + + result = await api_client.post("/users", json={"name": "New"}) + + assert result == {"id": 2, "created": True} + + +@pytest.mark.asyncio +async def test_retry_on_500(api_client): + """Test retry mechanism on 500 server error.""" + with aioresponses() as m: + # First 2 requests fail with 500, third succeeds + m.get("https://api.test.com/flaky", status=500) + m.get("https://api.test.com/flaky", status=500) + m.get("https://api.test.com/flaky", payload={"success": True}) + + result = await api_client.get("/flaky") + + assert result == {"success": True} + + +@pytest.mark.asyncio +async def test_retry_on_429_rate_limit(api_client): + """Test retry mechanism on 429 rate limit.""" + with aioresponses() as m: + m.get("https://api.test.com/throttled", status=429, headers={"Retry-After": "1"}) + m.get("https://api.test.com/throttled", payload={"ok": True}) + + result = await api_client.get("/throttled") + + assert result == {"ok": True} + + +@pytest.mark.asyncio +async def test_retry_on_network_timeout(api_client): + """Test retry on asyncio.TimeoutError (network timeout).""" + with aioresponses() as m: + # First call times out, second succeeds + m.get("https://api.test.com/slow", timeout=True) + m.get("https://api.test.com/slow", payload={"data": "value"}) + + result = await api_client.get("/slow") + + assert result == {"data": "value"} + + +@pytest.mark.asyncio +async def test_retry_on_connection_error(api_client): + """Test retry on aiohttp.ClientError.""" + with aioresponses() as m: + m.get("https://api.test.com/unstable", exception=ClientError("Connection lost")) + m.get("https://api.test.com/unstable", payload={"recovered": True}) + + result = await api_client.get("/unstable") + + assert result == {"recovered": True} + + +@pytest.mark.asyncio +async def test_max_retries_exceeded(api_client): + """Test that MaxRetriesExceededError is raised after all retries fail.""" + with aioresponses() as m: + # All requests fail with 500 + for _ in range(10): # More than max_retries + m.get("https://api.test.com/fail", status=500) + + with pytest.raises(MaxRetriesExceededError): + await api_client.get("/fail") + + +@pytest.mark.asyncio +async def test_should_retry_on_4xx_errors(): + """Test that 4xx errors (except 429) are NOT retried.""" + client = APIClient("https://api.test.com") + + # 404 should not be retried + assert not client._should_retry(None, 404) + # 400 should not be retried + assert not client._should_retry(None, 400) + # 403 should not be retried + assert not client._should_retry(None, 403) + # But 429 should be retried + assert client._should_retry(None, 429) + + +@pytest.mark.asyncio +async def test_should_retry_on_5xx_errors(): + """Test that 5xx errors ARE retried.""" + client = APIClient("https://api.test.com") + + assert client._should_retry(None, 500) + assert client._should_retry(None, 502) + assert client._should_retry(None, 503) + assert client._should_retry(None, 504) + + +@pytest.mark.asyncio +async def test_should_retry_on_network_errors(): + """Test that network errors ARE retried.""" + import asyncio + from aiohttp import ClientError + + client = APIClient("https://api.test.com") + + assert client._should_retry(asyncio.TimeoutError(), None) + assert client._should_retry(ClientError(), None) + + +@pytest.mark.asyncio +async def test_rate_limiting(api_client): + """Test that rate limiter restricts concurrent requests.""" + with aioresponses() as m: + # Set up responses + for i in range(5): + m.get(f"https://api.test.com/item/{i}", payload={"id": i}) + + # Make 5 concurrent requests + tasks = [api_client.get(f"/item/{i}") for i in range(5)] + results = await asyncio.gather(*tasks) + + assert len(results) == 5 + assert [r["id"] for r in results] == [0, 1, 2, 3, 4] + + +@pytest.mark.asyncio +async def test_session_reuse(api_client): + """Test that session is reused across requests.""" + with aioresponses() as m: + m.get("https://api.test.com/first", payload={"ok": True}) + m.get("https://api.test.com/second", payload={"ok": True}) + + await api_client.get("/first") + session1 = api_client._session + + await api_client.get("/second") + session2 = api_client._session + + # Same session instance + assert session1 is session2 + + +@pytest.mark.asyncio +async def test_context_manager(): + """Test that context manager closes session.""" + with aioresponses() as m: + m.get("https://api.test.com/test", payload={"ok": True}) + + async with APIClient("https://api.test.com") as client: + result = await client.get("/test") + assert result == {"ok": True} + # Session is open + assert not client._session.closed + + # Session is closed after context exit + assert client._session.closed + + +@pytest.mark.asyncio +async def test_put_and_delete_methods(): + """Test PUT and DELETE HTTP methods.""" + with aioresponses() as m: + m.put("https://api.test.com/items/1", payload={"updated": True}) + m.delete("https://api.test.com/items/1", status=204) + + client = APIClient("https://api.test.com") + + put_result = await client.put("/items/1", json={"name": "Updated"}) + assert put_result == {"updated": True} + + # DELETE with 204 returns no content (json() would fail) + m.delete("https://api.test.com/items/2", payload={"deleted": True}, status=200) + delete_result = await client.delete("/items/2") + assert delete_result == {"deleted": True} + + +@pytest.mark.asyncio +async def test_base_url_trailing_slash(): + """Test that trailing slash in base_url is handled correctly.""" + with aioresponses() as m: + m.get("https://api.test.com/test", payload={"ok": True}) + + # Trailing slash should be stripped + client = APIClient("https://api.test.com/") + result = await client.get("/test") + + assert result == {"ok": True} + + +# ==================== Parameterized tests for retryable statuses ==================== + +@pytest.mark.parametrize("status", [429, 500, 502, 503, 504]) +@pytest.mark.asyncio +async def test_retryable_status_codes(api_client, status): + """Test that all specified status codes are retried.""" + with aioresponses() as m: + # First call fails with retryable status, second succeeds + m.get("https://api.test.com/retry", status=status) + m.get("https://api.test.com/retry", payload={"success": True}) + + result = await api_client.get("/retry") + + # Success means retry worked (first response was error, second was success) + assert result == {"success": True} + + +# ==================== Edge cases ==================== + +@pytest.mark.asyncio +async def test_exponential_backoff_increases_delay(): + """Test that backoff delay increases with each retry attempt.""" + client = APIClient("https://api.test.com", base_delay=0.1, max_delay=10.0) + + delays = [client._calculate_delay(i) for i in range(5)] + + # Delays should generally increase (not strict due to jitter) + # But max delay should be bounded + assert all(d <= client.max_delay for d in delays) + + +@pytest.mark.asyncio +async def test_empty_response_body(api_client): + """Test handling of responses with empty body.""" + with aioresponses() as m: + # 204 No Content typically has no body + m.get("https://api.test.com/empty", status=204, body="") + + +# ==================== Logging tests ==================== + +@pytest.mark.asyncio +async def test_logging_on_success(api_client, caplog): + """Test that successful requests are logged.""" + import logging + caplog.set_level(logging.INFO) + + with aioresponses() as m: + m.get("https://api.test.com/test", payload={"ok": True}) + + await api_client.get("/test") + + # Check for success log + assert any("Success" in record.message for record in caplog.records) + + +# ==================== Configuration ==================== + +# Run tests with: pytest test_api_client.py -v +# Run with coverage: pytest test_api_client.py --cov=api_client --cov-report=html