-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimplementation_plan.md.resolved
More file actions
1391 lines (1149 loc) · 40.8 KB
/
implementation_plan.md.resolved
File metadata and controls
1391 lines (1149 loc) · 40.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Mikroservis Mimarisi ve API Gateway — Uçtan Uca Tasarım
## Genel Bakış
Bilişim Sistemleri Mühendisliği bitirme projesi için endüstri standartlarında bir **Mikroservis Mimarisi** tasarımı. Tek giriş noktası olan bir **API Gateway (Dispatcher)**, merkezi Redis tabanlı yetkilendirme, servis başına bağımsız MongoDB veritabanları, Docker ağ izolasyonu, TDD geliştirme disiplini, HATEOAS uyumlu REST API'ler ve Grafana ile izleme altyapısını kapsar.
**Teknoloji Yığını:** Python 3.11+ · FastAPI · Pytest · Redis · MongoDB · Docker · Locust · Prometheus · Grafana
---
## 1. Sistem Mimarisi Diyagramı
```mermaid
graph TB
subgraph EXTERNAL["🌐 Dış Ağ — public_network"]
CLIENT["🧑💻 İstemci<br/>(Browser / Postman / Locust)"]
end
subgraph GATEWAY_NET["🛡️ Gateway Ağı — gateway_network"]
DISPATCHER["⚡ Dispatcher<br/>(API Gateway)<br/>:8000"]
REDIS["🔴 Redis<br/>(Auth Token Store)<br/>:6379"]
PROMETHEUS["📊 Prometheus<br/>:9090"]
GRAFANA["📈 Grafana<br/>:3000"]
end
subgraph INTERNAL_NET["🔒 İç Ağ — internal_network"]
AUTH["🔐 Auth Service<br/>:8001"]
USER_SVC["👤 User Service<br/>:8002"]
PRODUCT_SVC["📦 Product Service<br/>:8003"]
MONGO_AUTH["🍃 MongoDB<br/>(auth_db)"]
MONGO_USER["🍃 MongoDB<br/>(user_db)"]
MONGO_PRODUCT["🍃 MongoDB<br/>(product_db)"]
end
CLIENT -->|"HTTP/HTTPS"| DISPATCHER
DISPATCHER -->|"Token Doğrulama"| REDIS
DISPATCHER -->|"Proxy"| AUTH
DISPATCHER -->|"Proxy"| USER_SVC
DISPATCHER -->|"Proxy"| PRODUCT_SVC
AUTH --> MONGO_AUTH
AUTH -->|"Token Oluştur/Sil"| REDIS
USER_SVC --> MONGO_USER
PRODUCT_SVC --> MONGO_PRODUCT
PROMETHEUS -->|"Scrape /metrics"| DISPATCHER
PROMETHEUS -->|"Scrape /metrics"| AUTH
PROMETHEUS -->|"Scrape /metrics"| USER_SVC
PROMETHEUS -->|"Scrape /metrics"| PRODUCT_SVC
GRAFANA -->|"Query"| PROMETHEUS
style EXTERNAL fill:#1a1a2e,stroke:#e94560,color:#fff
style GATEWAY_NET fill:#16213e,stroke:#0f3460,color:#fff
style INTERNAL_NET fill:#0f3460,stroke:#533483,color:#fff
style DISPATCHER fill:#e94560,stroke:#fff,color:#fff
style REDIS fill:#d63031,stroke:#fff,color:#fff
style AUTH fill:#00b894,stroke:#fff,color:#fff
style USER_SVC fill:#0984e3,stroke:#fff,color:#fff
style PRODUCT_SVC fill:#6c5ce7,stroke:#fff,color:#fff
```
### İstek Akış Diyagramı
```mermaid
sequenceDiagram
participant C as 🧑💻 İstemci
participant D as ⚡ Dispatcher
participant R as 🔴 Redis
participant A as 🔐 Auth Service
participant U as 👤 User Service
Note over C,U: 1. Oturum Açma (Login) Akışı
C->>D: POST /api/v1/auth/login {email, password}
D->>A: POST /login (iç ağ)
A->>A: Kimlik bilgisi doğrulama
A->>R: SET token → user_id (TTL: 3600s)
A-->>D: 200 {token, _links}
D-->>C: 200 {token, _links}
Note over C,U: 2. Korumalı Kaynak Erişimi
C->>D: GET /api/v1/users/me [Authorization: Bearer <token>]
D->>R: GET token → user_id
R-->>D: user_id (geçerli)
D->>U: GET /users/me [X-User-Id: user_id] (iç ağ)
U-->>D: 200 {user, _links}
D-->>C: 200 {user, _links}
Note over C,U: 3. Geçersiz Token Senaryosu
C->>D: GET /api/v1/users/me [Authorization: Bearer <expired>]
D->>R: GET token
R-->>D: null
D-->>C: 401 {detail: "Unauthorized", _links: {login: ...}}
```
---
## 2. Docker Ağ İzolasyonu Tasarımı
> [!IMPORTANT]
> Mikroservisler dışarıdan **asla erişilemez**. Yalnızca Dispatcher dış dünyaya port açar.
### Ağ Topolojisi
| Ağ Adı | Tip | Bağlı Konteynerler | Dış Port |
|---|---|---|---|
| `public_network` | bridge | Dispatcher, Grafana, Prometheus | 8000, 3000, 9090 |
| `gateway_network` | bridge | Dispatcher, Redis | — |
| `internal_network` | internal | Dispatcher, Auth, User, Product, MongoDB'ler | — |
```yaml
# docker-compose.yml — Ağ Tanımları
networks:
public_network:
driver: bridge
gateway_network:
driver: bridge
internal_network:
driver: bridge
internal: true # ← Dışarıdan erişimi tamamen engeller
```
### Servis-Ağ Eşlemesi
```yaml
services:
dispatcher:
ports:
- "8000:8000" # Tek dış erişim noktası
networks:
- public_network
- gateway_network
- internal_network
redis:
networks:
- gateway_network # Yalnızca Dispatcher erişir
# ports YOK → dışarıya kapalı
auth-service:
networks:
- internal_network # Yalnızca iç ağda
# ports YOK → dışarıya kapalı
user-service:
networks:
- internal_network
product-service:
networks:
- internal_network
mongo-auth:
networks:
- internal_network
mongo-user:
networks:
- internal_network
mongo-product:
networks:
- internal_network
```
> [!TIP]
> `internal: true` flag'i, Docker'ın bu ağdaki konteynerler için **dış dünyaya NAT/routing kuralı oluşturmamasını** sağlar. Bu sayede `auth-service`, `user-service`, `product-service` ve MongoDB'ler yalnızca `internal_network` üzerinden birbirleriyle ve Dispatcher ile iletişim kurabilir.
---
## 3. Proje Dosya Yapısı
```
microservice-graduation-project/
├── docker-compose.yml
├── docker-compose.monitoring.yml
├── .env.example
├── README.md
│
├── dispatcher/ # API Gateway
│ ├── Dockerfile
│ ├── requirements.txt
│ ├── app/
│ │ ├── __init__.py
│ │ ├── main.py # FastAPI uygulaması
│ │ ├── config.py # Ortam değişkenleri
│ │ ├── middleware/
│ │ │ ├── __init__.py
│ │ │ ├── auth_middleware.py # Redis token doğrulama
│ │ │ └── rate_limiter.py
│ │ ├── routes/
│ │ │ ├── __init__.py
│ │ │ ├── proxy.py # Servis yönlendirme
│ │ │ └── health.py
│ │ ├── services/
│ │ │ ├── __init__.py
│ │ │ └── service_registry.py # Servis keşfi
│ │ └── core/
│ │ ├── __init__.py
│ │ ├── exceptions.py # Merkezi hata yönetimi
│ │ └── hateoas.py # HATEOAS link builder
│ └── tests/
│ ├── __init__.py
│ ├── conftest.py # Shared fixtures
│ ├── test_auth_middleware.py
│ ├── test_proxy.py
│ ├── test_rate_limiter.py
│ └── test_hateoas.py
│
├── auth-service/ # Oturum Açma Servisi
│ ├── Dockerfile
│ ├── requirements.txt
│ ├── app/
│ │ ├── __init__.py
│ │ ├── main.py
│ │ ├── config.py
│ │ ├── controllers/
│ │ │ ├── __init__.py
│ │ │ └── auth_controller.py
│ │ ├── services/
│ │ │ ├── __init__.py
│ │ │ └── auth_service.py
│ │ ├── repositories/
│ │ │ ├── __init__.py
│ │ │ ├── base.py # Abstract Repository
│ │ │ └── user_credential_repo.py
│ │ ├── models/
│ │ │ ├── __init__.py
│ │ │ ├── domain.py # Pydantic domain modelleri
│ │ │ └── schemas.py # Request/Response şemaları
│ │ └── core/
│ │ ├── __init__.py
│ │ ├── exceptions.py
│ │ ├── hateoas.py
│ │ └── security.py # Password hashing
│ └── tests/
│ ├── conftest.py
│ ├── unit/
│ │ ├── test_auth_service.py
│ │ └── test_security.py
│ └── integration/
│ └── test_auth_api.py
│
├── user-service/ # Kullanıcı Servisi
│ ├── Dockerfile
│ ├── requirements.txt
│ ├── app/
│ │ ├── __init__.py
│ │ ├── main.py
│ │ ├── config.py
│ │ ├── controllers/
│ │ │ └── user_controller.py
│ │ ├── services/
│ │ │ └── user_service.py
│ │ ├── repositories/
│ │ │ ├── base.py
│ │ │ └── user_repo.py
│ │ ├── models/
│ │ │ ├── domain.py
│ │ │ └── schemas.py
│ │ └── core/
│ │ ├── exceptions.py
│ │ └── hateoas.py
│ └── tests/
│ ├── conftest.py
│ ├── unit/
│ │ └── test_user_service.py
│ └── integration/
│ └── test_user_api.py
│
├── product-service/ # Ürün Servisi
│ ├── (user-service ile aynı yapı)
│
├── shared/ # Paylaşılan kütüphane
│ ├── __init__.py
│ ├── base_repository.py # Abstract base class
│ ├── base_service.py
│ ├── hateoas.py # HATEOAS utilities
│ ├── exceptions.py # Ortak hata sınıfları
│ └── middleware.py # Ortak middleware'ler
│
├── monitoring/
│ ├── prometheus/
│ │ └── prometheus.yml
│ └── grafana/
│ └── dashboards/
│ └── dispatcher-dashboard.json
│
└── load-tests/
├── locustfile.py
└── k6/
└── load_test.js
```
---
## 4. TDD Stratejisi ve Commit Disiplini
### 4.1 Red-Green-Refactor Döngüsü
```mermaid
graph LR
RED["🔴 RED<br/>Başarısız test yaz"]
GREEN["🟢 GREEN<br/>Testi geçecek<br/>minimum kodu yaz"]
REFACTOR["🔵 REFACTOR<br/>Kodu iyileştir,<br/>testler hâlâ geçmeli"]
RED --> GREEN --> REFACTOR --> RED
style RED fill:#e74c3c,stroke:#c0392b,color:#fff
style GREEN fill:#27ae60,stroke:#219a52,color:#fff
style REFACTOR fill:#2980b9,stroke:#2471a3,color:#fff
```
### 4.2 Git Commit Stratejisi (Zaman Damgası Kanıtı)
TDD'nin kanıtlanması için test dosyasının **her zaman** uygulama kodundan önce commit edilmesi gerekir:
```bash
# Adım 1: Önce başarısız testi yaz ve commit et
git add auth-service/tests/unit/test_auth_service.py
git commit -m "test(auth): add failing test for login with invalid credentials
- RED phase: test_login_invalid_credentials expects 401 response
- Test written BEFORE implementation"
# Adım 2: Testi geçirecek kodu yaz ve commit et
git add auth-service/app/services/auth_service.py
git commit -m "feat(auth): implement login validation logic
- GREEN phase: minimum code to pass test_login_invalid_credentials
- Validates email/password against MongoDB credentials"
# Adım 3: Refactor ve commit et
git add auth-service/app/services/auth_service.py
git commit -m "refactor(auth): extract password hashing to security module
- REFACTOR phase: all tests still passing
- Moved bcrypt logic to core/security.py for reusability"
```
### 4.3 Pytest Yapılandırması
```ini
# pytest.ini (her servis kök dizininde)
[pytest]
testpaths = tests
python_files = test_*.py
python_classes = Test*
python_functions = test_*
markers =
unit: Unit testler (mock kullanır)
integration: Entegrasyon testleri (gerçek DB gerektirir)
e2e: Uçtan uca testler
addopts = -v --tb=short --strict-markers --cov=app --cov-report=term-missing
```
```python
# tests/conftest.py — Paylaşılan Fixture'lar
import pytest
from unittest.mock import AsyncMock, MagicMock
from httpx import AsyncClient, ASGITransport
from app.main import app
@pytest.fixture
def mock_mongo_collection():
"""MongoDB collection mock'u — unit testler için."""
collection = MagicMock()
collection.find_one = AsyncMock()
collection.insert_one = AsyncMock()
collection.update_one = AsyncMock()
collection.delete_one = AsyncMock()
return collection
@pytest.fixture
async def async_client():
"""FastAPI test istemcisi — integration testler için."""
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as client:
yield client
@pytest.fixture
def sample_user():
"""Test kullanıcı verisi."""
return {
"email": "test@example.com",
"password": "SecurePass123!",
"full_name": "Test Kullanıcı",
}
```
---
## 5. Hata Yönetimi — Sahte 200 Yasağı
> [!CAUTION]
> API asla başarısız bir işlem için `HTTP 200` dönmemelidir. Her hata durumu uygun HTTP durum koduyla temsil edilmelidir.
### Merkezi Hata Yapısı
```python
# shared/exceptions.py
from fastapi import HTTPException, Request
from fastapi.responses import JSONResponse
class AppException(Exception):
"""Tüm uygulama hatalarının temel sınıfı."""
def __init__(self, status_code: int, detail: str, error_code: str):
self.status_code = status_code
self.detail = detail
self.error_code = error_code
class NotFoundException(AppException):
def __init__(self, resource: str, resource_id: str):
super().__init__(
status_code=404,
detail=f"{resource} bulunamadı: {resource_id}",
error_code="RESOURCE_NOT_FOUND",
)
class UnauthorizedException(AppException):
def __init__(self, detail: str = "Geçersiz veya süresi dolmuş token"):
super().__init__(
status_code=401,
detail=detail,
error_code="UNAUTHORIZED",
)
class ConflictException(AppException):
def __init__(self, detail: str):
super().__init__(
status_code=409,
detail=detail,
error_code="CONFLICT",
)
# FastAPI exception handler olarak kayıt
async def app_exception_handler(request: Request, exc: AppException) -> JSONResponse:
return JSONResponse(
status_code=exc.status_code,
content={
"success": False,
"error": {
"code": exc.error_code,
"detail": exc.detail,
},
"_links": {
"self": {"href": str(request.url), "method": request.method},
"docs": {"href": "/docs"},
},
},
)
```
### HTTP Durum Kodu Haritası
| Durum | Kod | Kullanım |
|---|---|---|
| Başarılı oluşturma | `201 Created` | Kayıt, token oluşturma |
| Kaynak yok | `204 No Content` | Silme başarılı |
| Geçersiz istek | `400 Bad Request` | Validasyon hataları |
| Yetkisiz | `401 Unauthorized` | Token eksik/geçersiz |
| Yasak | `403 Forbidden` | Yetersiz yetki seviyesi |
| Bulunamadı | `404 Not Found` | Kaynak mevcut değil |
| Çakışma | `409 Conflict` | Duplicate email vb. |
| Sunucu hatası | `500 Internal Server Error` | Beklenmeyen hatalar |
| Servis kapalı | `503 Service Unavailable` | Downstream servis erişilemez |
---
## 6. RMM Seviye 3 — HATEOAS Uygulaması
### 6.1 HATEOAS Link Builder
```python
# shared/hateoas.py
from typing import Any
class HateoasLink:
"""Tek bir HATEOAS linkini temsil eder."""
def __init__(self, href: str, method: str = "GET", rel: str | None = None):
self.href = href
self.method = method
self.rel = rel
def to_dict(self) -> dict[str, str]:
result = {"href": self.href, "method": self.method}
if self.rel:
result["rel"] = self.rel
return result
class HateoasBuilder:
"""HATEOAS uyumlu response oluşturur."""
def __init__(self, base_url: str = "/api/v1"):
self.base_url = base_url
def build_response(
self, data: dict[str, Any], links: dict[str, HateoasLink]
) -> dict[str, Any]:
return {
**data,
"_links": {name: link.to_dict() for name, link in links.items()},
}
def collection_response(
self,
items: list[dict],
resource_name: str,
page: int = 1,
per_page: int = 20,
total: int = 0,
) -> dict[str, Any]:
total_pages = (total + per_page - 1) // per_page
base = f"{self.base_url}/{resource_name}"
links: dict[str, HateoasLink] = {
"self": HateoasLink(href=f"{base}?page={page}&per_page={per_page}"),
"create": HateoasLink(href=base, method="POST"),
}
if page > 1:
links["prev"] = HateoasLink(
href=f"{base}?page={page - 1}&per_page={per_page}"
)
if page < total_pages:
links["next"] = HateoasLink(
href=f"{base}?page={page + 1}&per_page={per_page}"
)
return {
"data": items,
"meta": {"page": page, "per_page": per_page, "total": total},
"_links": {k: v.to_dict() for k, v in links.items()},
}
```
### 6.2 Örnek HATEOAS Yanıtları
**Tek Kaynak — `GET /api/v1/users/6789`**
```json
{
"data": {
"id": "6789",
"email": "boran@example.com",
"full_name": "Boran Yılmaz",
"created_at": "2026-02-25T10:00:00Z"
},
"_links": {
"self": { "href": "/api/v1/users/6789", "method": "GET" },
"update": { "href": "/api/v1/users/6789", "method": "PUT" },
"delete": { "href": "/api/v1/users/6789", "method": "DELETE" },
"products": { "href": "/api/v1/users/6789/products", "method": "GET" },
"collection": { "href": "/api/v1/users", "method": "GET" }
}
}
```
**Koleksiyon — `GET /api/v1/products?page=2&per_page=10`**
```json
{
"data": [
{
"id": "p101",
"name": "Laptop",
"price": 29999.99,
"_links": {
"self": { "href": "/api/v1/products/p101", "method": "GET" },
"update": { "href": "/api/v1/products/p101", "method": "PUT" },
"owner": { "href": "/api/v1/users/6789", "method": "GET" }
}
}
],
"meta": { "page": 2, "per_page": 10, "total": 45 },
"_links": {
"self": { "href": "/api/v1/products?page=2&per_page=10", "method": "GET" },
"prev": { "href": "/api/v1/products?page=1&per_page=10", "method": "GET" },
"next": { "href": "/api/v1/products?page=3&per_page=10", "method": "GET" },
"create": { "href": "/api/v1/products", "method": "POST" }
}
}
```
**Hata Yanıtı — `GET /api/v1/users/9999`**
```json
{
"success": false,
"error": {
"code": "RESOURCE_NOT_FOUND",
"detail": "User bulunamadı: 9999"
},
"_links": {
"self": { "href": "/api/v1/users/9999", "method": "GET" },
"collection": { "href": "/api/v1/users", "method": "GET" },
"docs": { "href": "/docs" }
}
}
```
---
## 7. OOP / SOLID Prensipleri ve Katmanlaşma
### 7.1 Mimari Katmanlar
```mermaid
graph TD
subgraph PRESENTATION["📡 Sunum Katmanı (Controller)"]
CTRL["UserController<br/>FastAPI Router"]
end
subgraph BUSINESS["⚙️ İş Mantığı Katmanı (Service)"]
SVC["UserService<br/>İş Kuralları"]
end
subgraph DATA["💾 Veri Erişim Katmanı (Repository)"]
REPO["UserRepository<br/>MongoDB CRUD"]
end
subgraph DOMAIN["📦 Domain Katmanı (Models)"]
MODEL["User<br/>Pydantic Model"]
end
CTRL -->|"DTO/Schema"| SVC
SVC -->|"Domain Model"| REPO
REPO -->|"Document"| MODEL
style PRESENTATION fill:#e94560,stroke:#fff,color:#fff
style BUSINESS fill:#0984e3,stroke:#fff,color:#fff
style DATA fill:#00b894,stroke:#fff,color:#fff
style DOMAIN fill:#6c5ce7,stroke:#fff,color:#fff
```
### 7.2 SOLID Implementation
```python
# ─── S: Single Responsibility ──────────────────────────
# Her sınıf tek bir sorumluluğa sahip
# ─── O: Open/Closed ── I: Interface Segregation ────────
# ─── D: Dependency Inversion ───────────────────────────
from abc import ABC, abstractmethod
from typing import TypeVar, Generic
from pydantic import BaseModel
T = TypeVar("T", bound=BaseModel)
# ── Abstract Repository (Dependency Inversion + Open/Closed) ──
class AbstractRepository(ABC, Generic[T]):
"""Soyut Repository — tüm veri erişim sınıflarının arayüzü.
SOLID:
- D (Dependency Inversion): Service katmanı bu arayüze bağımlıdır,
somut MongoDB implementasyonuna değil.
- O (Open/Closed): Yeni bir DB (PostgreSQL vb.) eklemek için
mevcut kodu değiştirmeden yeni bir sınıf türetmek yeterli.
- I (Interface Segregation): Yalnızca CRUD operasyonları tanımlı.
"""
@abstractmethod
async def find_by_id(self, id: str) -> T | None: ...
@abstractmethod
async def find_all(self, skip: int = 0, limit: int = 20) -> list[T]: ...
@abstractmethod
async def create(self, entity: T) -> T: ...
@abstractmethod
async def update(self, id: str, entity: T) -> T | None: ...
@abstractmethod
async def delete(self, id: str) -> bool: ...
# ── Abstract Service ──
class AbstractService(ABC, Generic[T]):
"""Soyut Service — iş mantığı katmanı arayüzü."""
def __init__(self, repository: AbstractRepository[T]):
self._repository = repository # Dependency Injection
@abstractmethod
async def get_by_id(self, id: str) -> T: ...
@abstractmethod
async def get_all(self, page: int, per_page: int) -> tuple[list[T], int]: ...
# ── Concrete MongoDB Repository ──
from motor.motor_asyncio import AsyncIOMotorCollection
class MongoRepository(AbstractRepository[T]):
"""MongoDB implementasyonu.
SOLID:
- L (Liskov Substitution): AbstractRepository yerine kullanılabilir.
- S (Single Responsibility): Yalnızca MongoDB CRUD sorumlu.
"""
def __init__(self, collection: AsyncIOMotorCollection, model_class: type[T]):
self._collection = collection
self._model_class = model_class
async def find_by_id(self, id: str) -> T | None:
doc = await self._collection.find_one({"_id": id})
return self._model_class(**doc) if doc else None
async def find_all(self, skip: int = 0, limit: int = 20) -> list[T]:
cursor = self._collection.find().skip(skip).limit(limit)
return [self._model_class(**doc) async for doc in cursor]
async def create(self, entity: T) -> T:
doc = entity.model_dump(by_alias=True)
await self._collection.insert_one(doc)
return entity
async def update(self, id: str, entity: T) -> T | None:
result = await self._collection.update_one(
{"_id": id}, {"$set": entity.model_dump(exclude={"id"}, by_alias=True)}
)
return entity if result.modified_count else None
async def delete(self, id: str) -> bool:
result = await self._collection.delete_one({"_id": id})
return result.deleted_count > 0
# ── Concrete User Service ──
from shared.exceptions import NotFoundException
class UserService(AbstractService["User"]):
"""Kullanıcı iş mantığı.
SOLID:
- S: Yalnızca kullanıcı iş kuralları.
- D: AbstractRepository'ye bağımlı, MongoDB'ye değil.
"""
async def get_by_id(self, id: str) -> "User":
user = await self._repository.find_by_id(id)
if not user:
raise NotFoundException("User", id)
return user
async def get_all(self, page: int = 1, per_page: int = 20) -> tuple[list["User"], int]:
skip = (page - 1) * per_page
users = await self._repository.find_all(skip=skip, limit=per_page)
# Total count for pagination
total = await self._repository._collection.count_documents({})
return users, total
# ── Controller (FastAPI Router) ──
from fastapi import APIRouter, Depends
router = APIRouter(prefix="/users", tags=["Users"])
@router.get("/{user_id}")
async def get_user(user_id: str, service: UserService = Depends(get_user_service)):
user = await service.get_by_id(user_id)
return HateoasBuilder("/api/v1").build_response(
data=user.model_dump(),
links={
"self": HateoasLink(href=f"/api/v1/users/{user_id}"),
"update": HateoasLink(href=f"/api/v1/users/{user_id}", method="PUT"),
"delete": HateoasLink(href=f"/api/v1/users/{user_id}", method="DELETE"),
},
)
```
---
## 8. Dispatcher (API Gateway) Detaylı Tasarımı
### 8.1 Redis Tabanlı Merkezi Auth Middleware
```python
# dispatcher/app/middleware/auth_middleware.py
import redis.asyncio as redis
from fastapi import Request
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.responses import JSONResponse
# Public rotalar — auth gerektirmeyen
PUBLIC_PATHS = {
"/api/v1/auth/login",
"/api/v1/auth/register",
"/health",
"/docs",
"/openapi.json",
"/metrics",
}
class AuthMiddleware(BaseHTTPMiddleware):
"""Redis tabanlı merkezi yetkilendirme middleware'i."""
def __init__(self, app, redis_client: redis.Redis):
super().__init__(app)
self.redis = redis_client
async def dispatch(self, request: Request, call_next):
# Public path kontrolü
if request.url.path in PUBLIC_PATHS:
return await call_next(request)
# Token çıkarma
auth_header = request.headers.get("Authorization", "")
if not auth_header.startswith("Bearer "):
return JSONResponse(
status_code=401,
content={
"success": False,
"error": {"code": "MISSING_TOKEN", "detail": "Authorization header gerekli"},
"_links": {"login": {"href": "/api/v1/auth/login", "method": "POST"}},
},
)
token = auth_header.removeprefix("Bearer ").strip()
# Redis'ten token doğrulama
user_id = await self.redis.get(f"session:{token}")
if not user_id:
return JSONResponse(
status_code=401,
content={
"success": False,
"error": {"code": "INVALID_TOKEN", "detail": "Geçersiz veya süresi dolmuş token"},
"_links": {"login": {"href": "/api/v1/auth/login", "method": "POST"}},
},
)
# User ID'yi downstream servislere ilet
request.state.user_id = user_id.decode()
return await call_next(request)
```
### 8.2 Servis Proxy / Yönlendirme
```python
# dispatcher/app/routes/proxy.py
import httpx
from fastapi import APIRouter, Request
from fastapi.responses import JSONResponse
from app.services.service_registry import ServiceRegistry
router = APIRouter()
registry = ServiceRegistry()
@router.api_route(
"/api/v1/{service_name}/{path:path}",
methods=["GET", "POST", "PUT", "PATCH", "DELETE"],
)
async def proxy_request(service_name: str, path: str, request: Request):
"""Gelen istekleri uygun mikroservise yönlendirir."""
target_url = registry.resolve(service_name, path)
if not target_url:
return JSONResponse(
status_code=404,
content={
"success": False,
"error": {"code": "SERVICE_NOT_FOUND", "detail": f"Servis bulunamadı: {service_name}"},
"_links": {"docs": {"href": "/docs"}},
},
)
headers = dict(request.headers)
# İç ağ header'ları ekle
if hasattr(request.state, "user_id"):
headers["X-User-Id"] = request.state.user_id
headers["X-Forwarded-For"] = request.client.host
try:
async with httpx.AsyncClient(timeout=30.0) as client:
response = await client.request(
method=request.method,
url=target_url,
headers=headers,
content=await request.body(),
)
return JSONResponse(
status_code=response.status_code,
content=response.json(),
)
except httpx.ConnectError:
return JSONResponse(
status_code=503,
content={
"success": False,
"error": {"code": "SERVICE_UNAVAILABLE", "detail": f"{service_name} servisine erişilemiyor"},
"_links": {"health": {"href": "/health"}},
},
)
```
### 8.3 Service Registry
```python
# dispatcher/app/services/service_registry.py
from app.config import settings
class ServiceRegistry:
"""Servis adını iç ağ URL'sine çözümler."""
def __init__(self):
self._services: dict[str, str] = {
"auth": f"http://auth-service:{settings.AUTH_SERVICE_PORT}",
"users": f"http://user-service:{settings.USER_SERVICE_PORT}",
"products": f"http://product-service:{settings.PRODUCT_SERVICE_PORT}",
}
def resolve(self, service_name: str, path: str) -> str | None:
base_url = self._services.get(service_name)
if not base_url:
return None
return f"{base_url}/{path}"
def list_services(self) -> list[dict[str, str]]:
return [
{"name": name, "url": url}
for name, url in self._services.items()
]
```
---
## 9. Docker Compose Tam Yapılandırma
```yaml
# docker-compose.yml
version: "3.9"
services:
# ── API Gateway ──
dispatcher:
build: ./dispatcher
container_name: dispatcher
ports:
- "8000:8000"
environment:
- REDIS_URL=redis://redis:6379/0
- AUTH_SERVICE_PORT=8001
- USER_SERVICE_PORT=8002
- PRODUCT_SERVICE_PORT=8003
depends_on:
redis:
condition: service_healthy
auth-service:
condition: service_healthy
user-service:
condition: service_healthy
product-service:
condition: service_healthy
networks:
- public_network
- gateway_network
- internal_network
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8000/health"]
interval: 10s
timeout: 5s
retries: 3
# ── Redis (Auth Token Store) ──
redis:
image: redis:7-alpine
container_name: redis
command: redis-server --maxmemory 128mb --maxmemory-policy allkeys-lru
networks:
- gateway_network
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 5s
timeout: 3s
retries: 5
volumes:
- redis_data:/data
# ── Auth Service ──
auth-service:
build: ./auth-service
container_name: auth-service
environment:
- MONGO_URL=mongodb://mongo-auth:27017/auth_db
- REDIS_URL=redis://redis:6379/0
depends_on:
mongo-auth:
condition: service_healthy