chore(brain): ASTRA 성장 자산 동기화 — 기능 인벤토리·growth(약점프로필/학습큐)·일화기억·장기기억·회의록 원문
This commit is contained in:
@@ -0,0 +1,182 @@
|
||||
---
|
||||
id: wiki-2026-0508-django-signals
|
||||
title: Django Signals
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [Django Signal Framework, dispatch signals]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [django, python, observer-pattern, backend, decoupling]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: python
|
||||
framework: django-5
|
||||
---
|
||||
|
||||
# Django Signals
|
||||
|
||||
## 매 한 줄
|
||||
> **"매 in-process pub/sub for Django — observer pattern over the ORM lifecycle"**. Django signals 는 sender/receiver 의 decouple 하는 dispatch 메커니즘 — 2005 Django core 에 도입, 2026 현재 Django 5.1 LTS 까지 안정. 매 ORM hook (post_save, pre_delete) + custom signal 의 emit 의 standard way.
|
||||
|
||||
## 매 핵심
|
||||
|
||||
### 매 작동 원리
|
||||
- **django.dispatch.Signal**: receiver list 의 weakref 보관 — 매 GC safe.
|
||||
- **send() vs send_robust()**: send 의 raise on receiver error, send_robust 의 collect exceptions in result list — 매 production 의 send_robust 권장.
|
||||
- **Synchronous**: 매 in-process, in-thread — 매 transaction.on_commit() 통해 post-commit 의 schedule.
|
||||
- **Async receivers (5.0+)**: 매 async def receiver 의 native support.
|
||||
|
||||
### 매 built-in signals
|
||||
- **Model**: pre_save, post_save, pre_delete, post_delete, m2m_changed, pre_init, post_init.
|
||||
- **Request**: request_started, request_finished, got_request_exception.
|
||||
- **Auth**: user_logged_in, user_logged_out, user_login_failed.
|
||||
- **Migration**: pre_migrate, post_migrate.
|
||||
|
||||
### 매 응용
|
||||
1. Audit log — 매 model save 의 log 기록.
|
||||
2. Cache invalidation — 매 ORM update 시 cache key purge.
|
||||
3. Side-effect dispatch — 매 user signup → email send.
|
||||
|
||||
## 💻 패턴
|
||||
|
||||
### Receiver registration with @receiver
|
||||
```python
|
||||
# myapp/signals.py
|
||||
from django.db.models.signals import post_save
|
||||
from django.dispatch import receiver
|
||||
from django.conf import settings
|
||||
|
||||
from .models import Profile
|
||||
|
||||
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
|
||||
def create_user_profile(sender, instance, created, **kwargs):
|
||||
if created:
|
||||
Profile.objects.create(user=instance)
|
||||
```
|
||||
|
||||
### AppConfig.ready() 의 signal import
|
||||
```python
|
||||
# myapp/apps.py
|
||||
from django.apps import AppConfig
|
||||
|
||||
class MyAppConfig(AppConfig):
|
||||
name = "myapp"
|
||||
|
||||
def ready(self):
|
||||
from . import signals # noqa: F401 — register receivers
|
||||
```
|
||||
|
||||
### Custom signal
|
||||
```python
|
||||
# myapp/signals.py
|
||||
from django.dispatch import Signal
|
||||
|
||||
order_paid = Signal() # providing_args deprecated in 4.0+
|
||||
|
||||
# In a view/service after payment
|
||||
order_paid.send(sender=Order, order=order, amount=order.total)
|
||||
|
||||
# Receiver
|
||||
@receiver(order_paid)
|
||||
def send_receipt(sender, order, amount, **kwargs):
|
||||
EmailService.send_receipt(order, amount)
|
||||
```
|
||||
|
||||
### Transaction-safe side effects
|
||||
```python
|
||||
from django.db import transaction
|
||||
from django.db.models.signals import post_save
|
||||
|
||||
@receiver(post_save, sender=Order)
|
||||
def enqueue_fulfillment(sender, instance, created, **kwargs):
|
||||
if not created:
|
||||
return
|
||||
transaction.on_commit(
|
||||
lambda: fulfillment_queue.enqueue(instance.pk)
|
||||
)
|
||||
```
|
||||
|
||||
### Async receiver (Django 5.0+)
|
||||
```python
|
||||
from asgiref.sync import sync_to_async
|
||||
|
||||
@receiver(post_save, sender=Comment)
|
||||
async def notify_subscribers(sender, instance, **kwargs):
|
||||
await broadcast_to_channel(f"post-{instance.post_id}", {
|
||||
"event": "new_comment",
|
||||
"id": instance.pk,
|
||||
})
|
||||
```
|
||||
|
||||
### Robust dispatch with error collection
|
||||
```python
|
||||
results = order_paid.send_robust(sender=Order, order=order)
|
||||
for receiver_fn, response in results:
|
||||
if isinstance(response, Exception):
|
||||
logger.exception("receiver %s failed", receiver_fn, exc_info=response)
|
||||
```
|
||||
|
||||
### Cache invalidation
|
||||
```python
|
||||
from django.core.cache import cache
|
||||
from django.db.models.signals import post_save, post_delete
|
||||
|
||||
@receiver([post_save, post_delete], sender=Article)
|
||||
def purge_article_cache(sender, instance, **kwargs):
|
||||
cache.delete(f"article:{instance.pk}")
|
||||
cache.delete_pattern("articles:list:*") # if django-redis
|
||||
```
|
||||
|
||||
### Disconnect for testing
|
||||
```python
|
||||
import pytest
|
||||
from django.db.models.signals import post_save
|
||||
from myapp.signals import create_user_profile
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _silence_profile_signal():
|
||||
post_save.disconnect(create_user_profile, sender=User)
|
||||
yield
|
||||
post_save.connect(create_user_profile, sender=User)
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Cross-app decouple side-effect | Signal ✅ |
|
||||
| Same-app, deterministic flow | Direct method call (signal 불필요) |
|
||||
| Heavy work (email, ML inference) | Signal → enqueue Celery/RQ task |
|
||||
| Cross-process / cross-service | Kafka/RabbitMQ — 매 signal 은 in-process 만 |
|
||||
| Need ordering / replay | Outbox pattern + message broker |
|
||||
|
||||
**기본값**: signal 은 light decouple 만, heavy work 는 즉시 task queue 의 enqueue.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Observer-Pattern]]
|
||||
- 변형: [[Django-Signals]] · (blinker)
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: in-process decoupling 이 필요할 때, ORM lifecycle hook (post_save 등) 이 자연스러울 때, 매 third-party app 의 own model 의 alter 못할 때.
|
||||
**언제 X**: cross-service eventing — 매 Kafka/Outbox 의 use; complex workflow orchestration — 매 Celery chain / Temporal 의 use; testability 가 critical 한 critical path — 매 explicit service call 의 prefer.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Heavy work in receiver**: 매 sync send 면 request latency 의 block — Celery enqueue.
|
||||
- **Signals for in-app flow**: 매 traceability 의 lose — 매 explicit method call 의 use.
|
||||
- **No transaction.on_commit**: post_save 시점 의 transaction 미commit — race condition 발생.
|
||||
- **Forgetting weak=False**: lambda receiver 가 GC 의 collected — 매 module-level def 또는 weak=False.
|
||||
- **Test pollution**: signal 의 test 사이 의 leak — fixture 의 disconnect.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (docs.djangoproject.com/en/5.1/topics/signals/, Django source dispatch/dispatcher.py).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — Django 5.1 signal patterns + async receiver + transaction.on_commit |
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
---
|
||||
id: wiki-2026-0508-e-component-execution-loop
|
||||
title: E-component (Execution Loop)
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [Execution Loop, E-Loop, Agent Runtime Loop]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [agent, runtime, llm, architecture]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: Python
|
||||
framework: anthropic-sdk
|
||||
---
|
||||
|
||||
# E-component (Execution Loop)
|
||||
|
||||
## 매 한 줄
|
||||
> **"매 LLM agent 의 heartbeat"**. 매 EST (Execution / State / Tools) component triad 의 E — 매 model-call → 매 tool-dispatch → 매 result-feedback 의 inner loop. 매 Claude Agent SDK / OpenAI Assistants / LangGraph 매 same primitive.
|
||||
|
||||
## 매 핵심
|
||||
|
||||
### 매 mechanism
|
||||
1. Send messages + tool definitions to LLM.
|
||||
2. LLM 매 returns text + (optional) tool_use blocks.
|
||||
3. If tool_use: dispatch to T-component (Tool Registry), append tool_result to state.
|
||||
4. Loop until 매 stop_reason == "end_turn" or max_iterations.
|
||||
|
||||
### 매 components
|
||||
- **E (this)**: orchestrator — message-pump.
|
||||
- **S** (State Store): conversation history, scratch state.
|
||||
- **T** (Tool Registry): handler dispatch, schema validation.
|
||||
|
||||
### 매 응용
|
||||
1. Code agents (Claude Code, Cursor, Devin).
|
||||
2. Research agents (Perplexity, Deep Research).
|
||||
3. Workflow automation.
|
||||
|
||||
## 💻 패턴
|
||||
|
||||
### Minimal execution loop (Anthropic SDK 2026)
|
||||
```python
|
||||
from anthropic import Anthropic
|
||||
client = Anthropic()
|
||||
|
||||
def run(messages, tools, dispatch, max_iters=20):
|
||||
for _ in range(max_iters):
|
||||
resp = client.messages.create(
|
||||
model="claude-opus-4-7",
|
||||
max_tokens=4096,
|
||||
tools=tools,
|
||||
messages=messages,
|
||||
)
|
||||
messages.append({"role": "assistant", "content": resp.content})
|
||||
if resp.stop_reason == "end_turn":
|
||||
return resp
|
||||
tool_results = [
|
||||
{"type": "tool_result", "tool_use_id": b.id, "content": dispatch(b.name, b.input)}
|
||||
for b in resp.content if b.type == "tool_use"
|
||||
]
|
||||
messages.append({"role": "user", "content": tool_results})
|
||||
raise RuntimeError("max iterations exceeded")
|
||||
```
|
||||
|
||||
### Streaming variant
|
||||
```python
|
||||
with client.messages.stream(model="claude-opus-4-7", messages=messages, tools=tools) as stream:
|
||||
for event in stream:
|
||||
if event.type == "content_block_delta":
|
||||
print(event.delta.text, end="", flush=True)
|
||||
final = stream.get_final_message()
|
||||
```
|
||||
|
||||
### Tool dispatch (T-component plug-in)
|
||||
```python
|
||||
TOOLS = {
|
||||
"read_file": lambda input: open(input["path"]).read(),
|
||||
"list_dir": lambda input: os.listdir(input["path"]),
|
||||
}
|
||||
def dispatch(name, input):
|
||||
try: return TOOLS[name](input)
|
||||
except Exception as e: return f"Error: {e}"
|
||||
```
|
||||
|
||||
### Stop conditions
|
||||
```python
|
||||
STOP = {"end_turn", "stop_sequence", "max_tokens"}
|
||||
if resp.stop_reason in STOP: break
|
||||
```
|
||||
|
||||
### Prompt caching the system + tools
|
||||
```python
|
||||
resp = client.messages.create(
|
||||
model="claude-opus-4-7",
|
||||
system=[{"type": "text", "text": SYSTEM, "cache_control": {"type": "ephemeral"}}],
|
||||
tools=[{**t, "cache_control": {"type": "ephemeral"}} for t in tools],
|
||||
messages=messages,
|
||||
)
|
||||
```
|
||||
|
||||
### Budget guard
|
||||
```python
|
||||
total_tokens = 0
|
||||
while True:
|
||||
resp = client.messages.create(...)
|
||||
total_tokens += resp.usage.input_tokens + resp.usage.output_tokens
|
||||
if total_tokens > BUDGET: raise BudgetExceeded()
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Single-turn task | Direct API call |
|
||||
| Multi-tool task | E-loop |
|
||||
| Long-running workflow | E-loop + checkpointing (S) |
|
||||
|
||||
**기본값**: E-loop + prompt caching + budget guard + max-iter clamp.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Agent-Architecture]]
|
||||
- 변형: [[ReAct]]
|
||||
- 응용: [[LangGraph]]
|
||||
- Adjacent: [[S-component-State-Store]] · [[T-component-Tool-Registry]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: building agent runtime, multi-step tool-use task.
|
||||
**언제 X**: pure single-shot prompt (no tools, no state).
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **No max-iter cap**: 매 infinite-loop 의 risk.
|
||||
- **No budget guard**: 매 unbounded cost.
|
||||
- **Recreating system prompt per turn**: cache miss → 매 5-10x cost.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Anthropic Messages API docs, Claude Agent SDK).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — E-component FULL with SDK 2026 loop patterns |
|
||||
@@ -0,0 +1,200 @@
|
||||
---
|
||||
id: wiki-2026-0508-fastify
|
||||
title: Fastify
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [Fastify Framework, fastify.js]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [nodejs, web-framework, backend, performance]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: typescript
|
||||
framework: fastify-5
|
||||
---
|
||||
|
||||
# Fastify
|
||||
|
||||
## 매 한 줄
|
||||
> **"매 fastest Node.js web framework — schema-first, plugin-driven, zero-overhead"**. Fastify는 2016 Tomas Della Vedova 와 Matteo Collina 가 Express 의 throughput limit 을 깨고 schema-driven validation 을 native 로 만들기 위해 시작. 2026 현재 v5.x — Node 22 LTS, native fetch undici, Pino logging, async hooks 기반 plugin system 이 표준.
|
||||
|
||||
## 매 핵심
|
||||
|
||||
### 매 설계 원칙
|
||||
- **Schema-first**: 매 route 가 JSON Schema 의 declare — request/response validation + serialization 의 fast-json-stringify 통해 2-3x serialize speedup.
|
||||
- **Encapsulation**: 매 plugin 의 own scope — 매 child 가 parent 의 decorator 의 inherit 하되 sibling 의 isolated.
|
||||
- **Async/await native**: 매 handler 가 promise return — 매 reply.send() implicit.
|
||||
- **Zero-overhead logging**: Pino 의 default — 매 JSON structured, async write.
|
||||
|
||||
### 매 vs Express
|
||||
- 매 throughput: Fastify ~76k req/s vs Express ~13k req/s (Tech Empower 2026).
|
||||
- 매 type safety: TypeScript first-class — 매 FastifyInstance generic 의 typed plugin chain.
|
||||
- 매 ecosystem: 300+ official plugins (@fastify/*) — auth, cors, swagger, websocket, etc.
|
||||
|
||||
### 매 응용
|
||||
1. High-throughput REST/JSON API gateway.
|
||||
2. GraphQL server (Mercurius 통해).
|
||||
3. Microservice 의 internal RPC.
|
||||
|
||||
## 💻 패턴
|
||||
|
||||
### Server bootstrap with TypeBox schema
|
||||
```typescript
|
||||
import Fastify from 'fastify';
|
||||
import { TypeBoxTypeProvider, Type } from '@fastify/type-provider-typebox';
|
||||
|
||||
const app = Fastify({ logger: true }).withTypeProvider<TypeBoxTypeProvider>();
|
||||
|
||||
app.get('/users/:id', {
|
||||
schema: {
|
||||
params: Type.Object({ id: Type.String({ format: 'uuid' }) }),
|
||||
response: {
|
||||
200: Type.Object({ id: Type.String(), name: Type.String() }),
|
||||
},
|
||||
},
|
||||
}, async (req) => {
|
||||
// req.params.id is typed as string
|
||||
return { id: req.params.id, name: 'Ada' };
|
||||
});
|
||||
|
||||
await app.listen({ port: 3000, host: '0.0.0.0' });
|
||||
```
|
||||
|
||||
### Encapsulated plugin
|
||||
```typescript
|
||||
import fp from 'fastify-plugin';
|
||||
|
||||
export default fp(async (app) => {
|
||||
app.decorate('db', await connectPg(process.env.DATABASE_URL!));
|
||||
app.addHook('onClose', async (instance) => instance.db.end());
|
||||
}, { name: 'pg-plugin', dependencies: [] });
|
||||
|
||||
// Usage in route file
|
||||
app.register(async (scope) => {
|
||||
scope.get('/health', async (req) => {
|
||||
const r = await app.db.query('SELECT 1');
|
||||
return { ok: r.rowCount === 1 };
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
### JWT auth with @fastify/jwt
|
||||
```typescript
|
||||
import jwt from '@fastify/jwt';
|
||||
|
||||
app.register(jwt, { secret: process.env.JWT_SECRET! });
|
||||
|
||||
app.decorate('auth', async (req, reply) => {
|
||||
try { await req.jwtVerify(); }
|
||||
catch { reply.code(401).send({ error: 'unauthorized' }); }
|
||||
});
|
||||
|
||||
app.get('/me', { preHandler: app.auth }, async (req) => req.user);
|
||||
```
|
||||
|
||||
### Hooks lifecycle
|
||||
```typescript
|
||||
app.addHook('onRequest', async (req) => {
|
||||
req.startTime = process.hrtime.bigint();
|
||||
});
|
||||
|
||||
app.addHook('onResponse', async (req, reply) => {
|
||||
const elapsed = Number(process.hrtime.bigint() - req.startTime!) / 1e6;
|
||||
req.log.info({ url: req.url, elapsed_ms: elapsed }, 'request done');
|
||||
});
|
||||
```
|
||||
|
||||
### Streaming response
|
||||
```typescript
|
||||
import { Readable } from 'node:stream';
|
||||
|
||||
app.get('/export.ndjson', async (req, reply) => {
|
||||
reply.type('application/x-ndjson');
|
||||
const stream = Readable.from(generateRecords());
|
||||
return stream; // Fastify pipes automatically
|
||||
});
|
||||
|
||||
async function* generateRecords() {
|
||||
for await (const row of db.query('SELECT * FROM events')) {
|
||||
yield JSON.stringify(row) + '\n';
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### WebSocket plugin
|
||||
```typescript
|
||||
import websocket from '@fastify/websocket';
|
||||
|
||||
app.register(websocket);
|
||||
app.register(async (scope) => {
|
||||
scope.get('/ws', { websocket: true }, (socket, req) => {
|
||||
socket.on('message', (msg) => {
|
||||
socket.send(`echo: ${msg}`);
|
||||
});
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
### Error handling
|
||||
```typescript
|
||||
app.setErrorHandler((err, req, reply) => {
|
||||
if (err.validation) {
|
||||
reply.code(400).send({ error: 'validation', details: err.validation });
|
||||
return;
|
||||
}
|
||||
req.log.error(err);
|
||||
reply.code(500).send({ error: 'internal' });
|
||||
});
|
||||
```
|
||||
|
||||
### Graceful shutdown
|
||||
```typescript
|
||||
import closeWithGrace from 'close-with-grace';
|
||||
|
||||
closeWithGrace({ delay: 10_000 }, async ({ signal, err }) => {
|
||||
if (err) app.log.error(err);
|
||||
await app.close();
|
||||
});
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| High RPS JSON API | Fastify ✅ (default) |
|
||||
| Existing Express middleware ecosystem | Express + middie compat layer |
|
||||
| Type-safe schema-first | Fastify + TypeBox / Zod |
|
||||
| Edge runtime (Cloudflare Workers) | Hono (Fastify is Node-only) |
|
||||
| GraphQL | Fastify + Mercurius |
|
||||
|
||||
**기본값**: Fastify v5 + TypeBox + Pino — 매 Node 22 LTS 위.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Node.js]]
|
||||
- 변형: [[Hono]] · [[NestJS]]
|
||||
- 응용: [[Microservices]] · [[API-Gateway]]
|
||||
- Adjacent: [[OpenAPI]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: schema-driven REST/JSON API, microservice, high-throughput gateway, structured logging required.
|
||||
**언제 X**: edge runtime (Workers/Deno Deploy) — Hono 의 use; full opinionated DI/DDD framework wanted — NestJS 의 use.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **No schema**: route 의 schema-less 면 fast-json-stringify 의 benefit 의 lose — 매 always declare response schema.
|
||||
- **Sync handlers**: 매 use async — sync return 의 reply.send() forget 위험.
|
||||
- **Plugin without fastify-plugin**: encapsulation break 의 want 면 fp() wrap — 매 decorator parent 의 expose.
|
||||
- **Manual JSON.stringify**: 매 reply.send(obj) — fast-json-stringify 의 use.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (fastify.dev v5 docs, Tech Empower Round 22 2026).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — Fastify v5 patterns + TypeBox/Pino/WebSocket recipes |
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
---
|
||||
id: wiki-2026-0508-kiss-keep-it-simple-stupid
|
||||
title: "KISS (Keep It Simple, Stupid)"
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [KISS Principle, Keep It Simple]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.95
|
||||
verification_status: applied
|
||||
tags: [principle, design, software-engineering]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: any
|
||||
framework: any
|
||||
---
|
||||
|
||||
# KISS (Keep It Simple, Stupid)
|
||||
|
||||
## 매 한 줄
|
||||
> **"매 simplest-thing-that-could-possibly-work"**. 매 1960s Lockheed Skunk Works 의 Kelly Johnson 의 aerospace heuristic → 매 software 매 universal 의 design principle. 매 sibling: YAGNI, Worse-is-Better, Occam's Razor.
|
||||
|
||||
## 매 핵심
|
||||
|
||||
### 매 mechanism
|
||||
- 매 each abstraction 의 cognitive cost 의 measure.
|
||||
- 매 minimum-viable design → 매 iterate.
|
||||
- 매 complexity 매 emergent, never additive cheap.
|
||||
|
||||
### 매 forms
|
||||
- **Code**: fewer lines, fewer abstractions, fewer dependencies.
|
||||
- **API**: fewer endpoints, fewer params, fewer states.
|
||||
- **System**: fewer services, fewer protocols, fewer config knobs.
|
||||
|
||||
### 매 응용
|
||||
1. Pre-mature abstraction avoidance (Rule of Three).
|
||||
2. Boring-tech preference (PostgreSQL > custom DB).
|
||||
3. Monolith-first (Fowler), microservices later if needed.
|
||||
|
||||
## 💻 패턴
|
||||
|
||||
### KISS 매 too-complex (anti)
|
||||
```ts
|
||||
// Over-engineered: factory + builder + strategy for "add 2 numbers"
|
||||
class AdderFactory {
|
||||
static create(strategy: AddStrategy): Adder { /* ... */ }
|
||||
}
|
||||
```
|
||||
|
||||
### KISS 매 right
|
||||
```ts
|
||||
const add = (a: number, b: number) => a + b;
|
||||
```
|
||||
|
||||
### Service split: simple-first
|
||||
```ts
|
||||
// Simple: 1 service, postgres
|
||||
app.post('/order', async (req, res) => {
|
||||
const order = await db.orders.create(req.body);
|
||||
await sendEmail(order);
|
||||
res.json(order);
|
||||
});
|
||||
|
||||
// Only when justified by load/team-size: split into microservices.
|
||||
```
|
||||
|
||||
### Dependency minimalism
|
||||
```bash
|
||||
# package.json 매 audit — every dep is liability
|
||||
npm-check --unused
|
||||
depcheck
|
||||
```
|
||||
|
||||
### Config 매 default-driven
|
||||
```ts
|
||||
// Bad: 27 required env vars
|
||||
// Good: smart defaults, override only when needed
|
||||
const PORT = process.env.PORT ?? 3000;
|
||||
const DB_URL = process.env.DATABASE_URL ?? 'postgres://localhost/dev';
|
||||
```
|
||||
|
||||
### Naming for clarity
|
||||
```ts
|
||||
// Bad
|
||||
function p(d: any[]) { /* ... */ }
|
||||
|
||||
// Good
|
||||
function paginate(items: Item[]): Page<Item> { /* ... */ }
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Choice |
|
||||
|---|---|
|
||||
| First version | Simplest possible, single file if needed |
|
||||
| 매 second feature 의 same shape | Still don't abstract |
|
||||
| 매 third 의 same shape (Rule of Three) | Now abstract |
|
||||
|
||||
**기본값**: Inline the code. Abstract only when 매 third 의 same pattern emerges.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Software-Design-Principles]]
|
||||
- 변형: [[YAGNI]]
|
||||
- Adjacent: [[Premature-Optimization]] · [[Rule-of-Three]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: design review, architecture decision, code review (cut complexity).
|
||||
**언제 X**: 매 inherent-complexity domain (compilers, crypto, distributed consensus) 매 simplification 매 wrong-target.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Premature abstraction**: 1 use 의 abstraction 매 wrong shape.
|
||||
- **Configuration explosion**: every-flag-as-knob.
|
||||
- **Microservices day-one**: 매 distributed monolith 의 invitation.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Kelly Johnson — Lockheed Skunk Works; Rich Hickey — Simple Made Easy talk; Worse-is-Better essay).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — KISS FULL content with anti-patterns |
|
||||
+163
@@ -0,0 +1,163 @@
|
||||
---
|
||||
id: wiki-2026-0508-preserving-state-in-procedural-w
|
||||
title: Preserving State in Procedural Worlds
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [Procedural World Persistence, Seed-Based State]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [procedural-generation, game-dev, state, persistence]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: TypeScript
|
||||
framework: any
|
||||
---
|
||||
|
||||
# Preserving State in Procedural Worlds
|
||||
|
||||
## 매 한 줄
|
||||
> **"매 infinite-world 의 finite-memory tradeoff"**. 매 Minecraft, No Man's Sky, Dwarf Fortress 매 procedural-generated world → 매 player modifications 매 persist 매 only-visited chunks. 매 seed + delta-overlay 의 standard pattern.
|
||||
|
||||
## 매 핵심
|
||||
|
||||
### 매 problem
|
||||
- World 매 effectively infinite (2^64 seed space).
|
||||
- Cannot store every chunk (memory + disk).
|
||||
- But player modifications must survive.
|
||||
|
||||
### 매 standard pattern
|
||||
1. Deterministic seed-based generator G(seed, x, y, z) → chunk.
|
||||
2. Delta overlay D(x, y, z) → player edits relative to G.
|
||||
3. On load: chunk = G(seed, ...) ⊕ D(...).
|
||||
4. Disk: store only non-empty D entries.
|
||||
|
||||
### 매 응용
|
||||
1. Sandbox games (Minecraft, Terraria).
|
||||
2. Roguelikes (Dwarf Fortress, Caves of Qud).
|
||||
3. Open-world MMOs (No Man's Sky regions).
|
||||
|
||||
## 💻 패턴
|
||||
|
||||
### Seed-based deterministic generator (Perlin/Simplex)
|
||||
```ts
|
||||
import { createNoise2D } from 'simplex-noise';
|
||||
|
||||
class WorldGen {
|
||||
private noise2D: ReturnType<typeof createNoise2D>;
|
||||
constructor(seed: number) {
|
||||
const rng = mulberry32(seed);
|
||||
this.noise2D = createNoise2D(rng);
|
||||
}
|
||||
height(x: number, z: number): number {
|
||||
return Math.floor(64 + 32 * this.noise2D(x * 0.01, z * 0.01));
|
||||
}
|
||||
}
|
||||
function mulberry32(a: number) { return () => { /* ... */ }; }
|
||||
```
|
||||
|
||||
### Delta-overlay storage (sparse)
|
||||
```ts
|
||||
type ChunkKey = `${number},${number}`; // chunk coord
|
||||
type BlockKey = `${number},${number},${number}`; // block coord within chunk
|
||||
|
||||
class DeltaStore {
|
||||
private deltas = new Map<ChunkKey, Map<BlockKey, BlockId | null>>();
|
||||
|
||||
set(cx: number, cz: number, bx: number, by: number, bz: number, b: BlockId | null) {
|
||||
const key: ChunkKey = `${cx},${cz}`;
|
||||
let chunk = this.deltas.get(key);
|
||||
if (!chunk) this.deltas.set(key, (chunk = new Map()));
|
||||
chunk.set(`${bx},${by},${bz}`, b);
|
||||
}
|
||||
|
||||
applyTo(cx: number, cz: number, generated: Block[][][]): Block[][][] {
|
||||
const chunk = this.deltas.get(`${cx},${cz}`);
|
||||
if (!chunk) return generated;
|
||||
for (const [bk, b] of chunk) {
|
||||
const [bx, by, bz] = bk.split(',').map(Number);
|
||||
generated[bx][by][bz] = b ?? AIR;
|
||||
}
|
||||
return generated;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Chunk persistence (NBT-style binary)
|
||||
```ts
|
||||
import { writeFile } from 'fs/promises';
|
||||
import { gzipSync } from 'zlib';
|
||||
|
||||
async function saveChunk(cx: number, cz: number, store: DeltaStore) {
|
||||
const data = store.deltas.get(`${cx},${cz}`);
|
||||
if (!data || data.size === 0) return;
|
||||
const buf = encodeNBT([...data.entries()]);
|
||||
await writeFile(`world/c.${cx}.${cz}.dat`, gzipSync(buf));
|
||||
}
|
||||
```
|
||||
|
||||
### LRU chunk cache (memory bound)
|
||||
```ts
|
||||
import LRU from 'lru-cache';
|
||||
const cache = new LRU<ChunkKey, Chunk>({ max: 256, dispose: (chunk, k) => persist(k, chunk) });
|
||||
|
||||
function getChunk(cx: number, cz: number): Chunk {
|
||||
const key: ChunkKey = `${cx},${cz}`;
|
||||
let c = cache.get(key);
|
||||
if (!c) {
|
||||
c = applyDeltas(generate(cx, cz), key);
|
||||
cache.set(key, c);
|
||||
}
|
||||
return c;
|
||||
}
|
||||
```
|
||||
|
||||
### Player-modification log (event-sourced variant)
|
||||
```ts
|
||||
type Edit = { t: number; x: number; y: number; z: number; before: BlockId; after: BlockId };
|
||||
const log: Edit[] = [];
|
||||
function setBlock(x: number, y: number, z: number, after: BlockId) {
|
||||
const before = world.get(x, y, z);
|
||||
log.push({ t: Date.now(), x, y, z, before, after });
|
||||
world.set(x, y, z, after);
|
||||
}
|
||||
// rebuild deltas by replaying log (audit + rollback)
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Pattern |
|
||||
|---|---|
|
||||
| Few edits, infinite world | Seed + sparse delta |
|
||||
| Heavy editing, finite world | Full chunk storage |
|
||||
| Audit / rollback needed | Event-sourced log |
|
||||
| Multi-player concurrent | Authoritative server + delta sync |
|
||||
|
||||
**기본값**: Seed + delta-overlay + LRU cache + on-demand disk persistence.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Procedural-Generation]]
|
||||
- 변형: [[Event-Sourcing]]
|
||||
- Adjacent: [[Perlin-Noise]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: voxel/sandbox game architecture, infinite-world design, save-system design.
|
||||
**언제 X**: linear-level games (use whole-state save).
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Storing every chunk**: 매 disk explosion.
|
||||
- **Non-deterministic generator**: 매 seed-replay 매 broken.
|
||||
- **No LRU bound**: 매 OOM on long sessions.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Minecraft Anvil format docs, Perlin noise paper, "Dwarf Fortress" GDC talks).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — Procedural state preservation FULL with seed+delta pattern |
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
---
|
||||
id: wiki-2026-0508-prisons-and-self-correction
|
||||
title: Prisons and Self-Correction
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [Penitentiary System, Carceral Reform]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.85
|
||||
verification_status: applied
|
||||
tags: [criminology, justice, history, sociology]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: n/a
|
||||
framework: n/a
|
||||
---
|
||||
|
||||
# Prisons and Self-Correction
|
||||
|
||||
## 매 한 줄
|
||||
> **"매 1790s Quaker 의 penitence-as-cure 의 invention"**. 매 Eastern State Penitentiary (1829) 의 solitary-confinement model 매 "self-correction through silent reflection" → 매 Foucault (1975 Discipline & Punish) 의 critique → 매 2026 의 evidence-based recidivism reduction debate.
|
||||
|
||||
## 매 핵심
|
||||
|
||||
### 매 historical arc
|
||||
1. Pre-1790: corporal/capital punishment, public execution.
|
||||
2. 1790-1830: Quaker penitentiary (Pennsylvania system) — isolation + silence.
|
||||
3. 1830-1900: Auburn system — silent congregate labor.
|
||||
4. 1900s: rehabilitation ideal, parole.
|
||||
5. 1970s-: "tough on crime" backlash, mass incarceration (esp. US).
|
||||
6. 2010s-: evidence-based reform, Norway model (Halden), restorative justice.
|
||||
|
||||
### 매 modern data
|
||||
- US incarceration rate: 매 ~600/100k (2024) — 매 highest among OECD.
|
||||
- Norway recidivism: 매 ~20% within 2y; US: 매 ~67%.
|
||||
- RAND meta-analysis: education programs 매 reduce recidivism 매 ~43%.
|
||||
|
||||
### 매 응용
|
||||
1. Policy design (recidivism reduction, sentencing reform).
|
||||
2. Software (case management, predictive risk — see fairness debate).
|
||||
3. Restorative-justice programs.
|
||||
|
||||
## 💻 패턴
|
||||
|
||||
### Recidivism modeling (responsible)
|
||||
```python
|
||||
import pandas as pd
|
||||
from sklearn.linear_model import LogisticRegression
|
||||
from fairlearn.metrics import demographic_parity_difference
|
||||
|
||||
df = pd.read_csv('release_cohort.csv')
|
||||
X = df[['age_at_release', 'prior_arrests', 'program_completed', 'employment_post']]
|
||||
y = df['rearrest_within_3y']
|
||||
|
||||
model = LogisticRegression().fit(X, y)
|
||||
pred = model.predict(X)
|
||||
|
||||
# fairness audit
|
||||
print('DP diff (race):', demographic_parity_difference(y, pred, sensitive_features=df['race']))
|
||||
```
|
||||
|
||||
### Risk-tool transparency (COMPAS critique)
|
||||
```
|
||||
ProPublica 2016 audit:
|
||||
- Black defendants: 45% false-positive (predicted re-offend, didn't)
|
||||
- White defendants: 23% false-positive
|
||||
→ disparate-impact even when "race-blind"
|
||||
```
|
||||
|
||||
### Halden Prison design principles (Norway)
|
||||
```
|
||||
1. Normalize: cell ≈ dorm room, common kitchens.
|
||||
2. Education + work as default activity.
|
||||
3. Short sentences (max 21y for most crimes).
|
||||
4. Officer-inmate ratio high; relational, not custodial.
|
||||
5. Pre-release housing transition.
|
||||
```
|
||||
|
||||
### Restorative-justice circle script
|
||||
```
|
||||
1. Storytelling: harmed party speaks first.
|
||||
2. Acknowledgment: harm-doer reflects.
|
||||
3. Community impact discussion.
|
||||
4. Repair plan: agreed actions, timeline.
|
||||
5. Follow-up at 30/90 days.
|
||||
```
|
||||
|
||||
### Education program ROI (RAND 2013)
|
||||
```
|
||||
Cost per inmate education: $1,400-1,744 / year
|
||||
Reduced recidivism savings: ~$5/$1 invested
|
||||
3-year recidivism: 43% reduction
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Reform policy design | Norway/Halden + restorative |
|
||||
| Recidivism prediction | Avoid black-box; favor interpretable + fairness audits |
|
||||
| Drug offenses | Treatment courts, not incarceration |
|
||||
|
||||
**기본값**: Education + employment + housing transition + restorative practices.
|
||||
|
||||
## 🔗 Graph
|
||||
- 변형: [[Restorative-Justice]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: policy analysis, criminology discussion, fairness-aware ML in criminal justice.
|
||||
**언제 X**: 매 software-only topic (this is policy/sociology).
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Black-box risk-assessment**: 매 unaudited disparate impact.
|
||||
- **Solitary as default**: 매 mental-health damage 의 evidence.
|
||||
- **Long sentences as deterrent**: 매 evidence weak; certainty > severity.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Foucault — Discipline & Punish; Norway corrections white papers; RAND 2013 education meta-analysis; ProPublica COMPAS).
|
||||
- 신뢰도 A-.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — Prisons & Self-Correction FULL content |
|
||||
@@ -0,0 +1,205 @@
|
||||
---
|
||||
id: wiki-2026-0508-public-apis
|
||||
title: Public APIs
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [Public API, External API, Open API, Developer API]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [backend, api, rest, graphql, design]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: typescript
|
||||
framework: hono
|
||||
---
|
||||
|
||||
# Public APIs
|
||||
|
||||
## 매 한 줄
|
||||
> **"매 API 매 product"**. Public API 매 외부 developer-facing — versioning · auth · rate-limit · docs · SLA 매 first-class. 2026 stack: REST + OpenAPI 3.1, GraphQL Federation v2, gRPC for 내부, MCP for AI agents — Stripe · GitHub · Twilio 매 reference.
|
||||
|
||||
## 매 핵심
|
||||
|
||||
### 매 Design pillars
|
||||
- **Versioning**: URL(`/v1`) · header(`API-Version: 2026-05-01`, Stripe). 매 deprecation policy.
|
||||
- **Auth**: OAuth2 · API key · JWT · mTLS. Per-key scopes.
|
||||
- **Rate limit**: token bucket per key/IP. `Retry-After` · `X-RateLimit-*` headers.
|
||||
- **Pagination**: cursor (preferred) > offset. 매 stable · efficient.
|
||||
- **Errors**: RFC 7807 Problem Details. 매 stable error codes.
|
||||
- **Idempotency**: `Idempotency-Key` header (Stripe pattern).
|
||||
- **Docs**: OpenAPI 3.1 + interactive (Scalar / Redocly).
|
||||
|
||||
### 매 Protocol selection
|
||||
- **REST + JSON**: 매 default · widest compat.
|
||||
- **GraphQL**: 매 client-shaped queries · over-fetch 의 X.
|
||||
- **gRPC**: 매 internal · low-latency · binary.
|
||||
- **MCP**: 매 LLM agent tool exposure (2025+).
|
||||
- **Webhooks**: server-push · async events.
|
||||
|
||||
### 매 응용
|
||||
1. SaaS public API (Stripe, GitHub, Twilio).
|
||||
2. Platform / marketplace.
|
||||
3. Mobile/web client backend.
|
||||
4. Partner integration.
|
||||
|
||||
## 💻 패턴
|
||||
|
||||
### REST endpoint with OpenAPI (Hono + Zod)
|
||||
```typescript
|
||||
import { Hono } from 'hono';
|
||||
import { z } from 'zod';
|
||||
import { describeRoute } from 'hono-openapi/zod';
|
||||
|
||||
const app = new Hono();
|
||||
|
||||
const Order = z.object({
|
||||
id: z.string().uuid(),
|
||||
amount_cents: z.number().int().nonnegative(),
|
||||
currency: z.enum(['USD','EUR','KRW']),
|
||||
});
|
||||
|
||||
app.get('/v1/orders/:id',
|
||||
describeRoute({
|
||||
summary: 'Get order',
|
||||
responses: { 200: { content: { 'application/json': { schema: Order } } } },
|
||||
}),
|
||||
async (c) => {
|
||||
const o = await db.orders.find(c.req.param('id'));
|
||||
if (!o) return c.json({ type:'/errors/not-found', title:'Order not found' }, 404);
|
||||
return c.json(o);
|
||||
});
|
||||
```
|
||||
|
||||
### Cursor pagination
|
||||
```typescript
|
||||
// GET /v1/orders?limit=50&cursor=opaque
|
||||
app.get('/v1/orders', async (c) => {
|
||||
const limit = Math.min(Number(c.req.query('limit') ?? 50), 100);
|
||||
const cursor = c.req.query('cursor');
|
||||
const after = cursor ? decode(cursor) : null; // {id, created_at}
|
||||
const rows = await db.orders.list({ after, limit: limit + 1 });
|
||||
const hasMore = rows.length > limit;
|
||||
const page = rows.slice(0, limit);
|
||||
return c.json({
|
||||
data: page,
|
||||
next_cursor: hasMore ? encode(page[page.length-1]) : null,
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
### Rate limit (Cloudflare/Redis token bucket)
|
||||
```typescript
|
||||
async function rateLimit(key: string, capacity = 100, refillPerSec = 10) {
|
||||
const now = Date.now()/1000;
|
||||
const lua = `
|
||||
local b = redis.call('HMGET', KEYS[1], 'tokens','ts')
|
||||
local tokens = tonumber(b[1]) or tonumber(ARGV[1])
|
||||
local ts = tonumber(b[2]) or tonumber(ARGV[3])
|
||||
local refill = (tonumber(ARGV[3]) - ts) * tonumber(ARGV[2])
|
||||
tokens = math.min(tonumber(ARGV[1]), tokens + refill)
|
||||
if tokens < 1 then return 0 end
|
||||
redis.call('HMSET', KEYS[1], 'tokens', tokens-1, 'ts', ARGV[3])
|
||||
return 1
|
||||
`;
|
||||
return redis.eval(lua, 1, key, capacity, refillPerSec, now);
|
||||
}
|
||||
```
|
||||
|
||||
### Idempotency-Key (Stripe pattern)
|
||||
```typescript
|
||||
app.post('/v1/payments', async (c) => {
|
||||
const idem = c.req.header('Idempotency-Key');
|
||||
if (!idem) return c.json({ error: 'idempotency_key_required' }, 400);
|
||||
const cached = await idemStore.get(idem);
|
||||
if (cached) return c.json(cached.body, cached.status);
|
||||
const result = await chargeCard(await c.req.json());
|
||||
await idemStore.put(idem, { status: 200, body: result }, { ttl: 86400 });
|
||||
return c.json(result);
|
||||
});
|
||||
```
|
||||
|
||||
### Webhook with HMAC sig (verified)
|
||||
```typescript
|
||||
import crypto from 'node:crypto';
|
||||
function verify(payload: string, sig: string, secret: string) {
|
||||
const expected = crypto.createHmac('sha256', secret).update(payload).digest('hex');
|
||||
return crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(expected));
|
||||
}
|
||||
```
|
||||
|
||||
### Versioning by header (Stripe-style)
|
||||
```typescript
|
||||
app.use('*', async (c, next) => {
|
||||
const v = c.req.header('Stripe-Version') ?? '2026-05-01';
|
||||
c.set('apiVersion', v);
|
||||
await next();
|
||||
});
|
||||
// 매 handler 매 version-aware shape transform.
|
||||
```
|
||||
|
||||
### Problem Details error (RFC 7807)
|
||||
```typescript
|
||||
function problem(status: number, type: string, title: string, detail?: string) {
|
||||
return new Response(
|
||||
JSON.stringify({ type, title, status, detail }),
|
||||
{ status, headers: { 'Content-Type': 'application/problem+json' } }
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### MCP server (AI agent tool)
|
||||
```typescript
|
||||
// 매 Public API 매 LLM-callable
|
||||
import { McpServer } from '@modelcontextprotocol/sdk/server';
|
||||
const server = new McpServer({ name: 'orders-api', version: '1.0.0' });
|
||||
server.tool('get_order', { id: z.string() }, async ({ id }) => {
|
||||
const o = await fetch(`https://api.acme.com/v1/orders/${id}`).then(r => r.json());
|
||||
return { content: [{ type: 'text', text: JSON.stringify(o) }] };
|
||||
});
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 요건 | Choice |
|
||||
|---|---|
|
||||
| External developer-facing | REST + OpenAPI 3.1 |
|
||||
| Client-shaped queries | GraphQL |
|
||||
| Internal RPC | gRPC |
|
||||
| AI agent tool | MCP |
|
||||
| Async event push | Webhooks |
|
||||
| File upload large | Resumable (tus) |
|
||||
| Real-time | SSE / WebSockets |
|
||||
|
||||
**기본값**: REST + OpenAPI + Idempotency-Key + cursor pagination.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Backend Architecture]] · [[API Design]]
|
||||
- 변형: [[REST]] · [[gRPC]] · [[MCP]]
|
||||
- 응용: [[OpenAPI - Swagger]]
|
||||
- Adjacent: [[Webhooks and Notifications]] · [[Rate Limiting]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: OpenAPI spec generation, error-shape design, 매 SDK scaffolding.
|
||||
**언제 X**: 매 production rate-limit policy 의 직접 결정 — 매 traffic data 의 review.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **No versioning**: breaking change 매 직격탄.
|
||||
- **Random error shapes**: client 매 parse 못 함 — RFC 7807 의 사용.
|
||||
- **Offset pagination on huge tables**: 매 deep scan.
|
||||
- **Sync auth check on hot path**: cache JWT verification.
|
||||
- **No `Idempotency-Key`**: 매 retry 매 double charge.
|
||||
- **Leaking internal IDs**: opaque · cursor · UUID 의 사용.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Stripe API docs 2026; GitHub API docs; *API Design Patterns* JJ Geewax).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — full content (pillars + 8 patterns) |
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
---
|
||||
id: wiki-2026-0508-동적-정적-코드-분석-static-dynamic-code-
|
||||
title: 동적-정적 코드 분석 (Static-Dynamic Code Analysis)
|
||||
category: 10_Wiki/Topics
|
||||
status: duplicate
|
||||
canonical_id: static-dynamic-code-analysis
|
||||
duplicate_of: "[[Static-Dynamic-Code-Analysis]]"
|
||||
aliases: []
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
verification_status: redirected
|
||||
tags: [duplicate, static-analysis, dynamic-analysis]
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
---
|
||||
|
||||
# 동적-정적 코드 분석 (Static-Dynamic Code Analysis)
|
||||
|
||||
> **이 문서는 [[Static-Dynamic-Code-Analysis]] 의 중복본입니다.** Canonical 문서로 redirect.
|
||||
|
||||
## 핵심 요약
|
||||
- 매 SAST (정적) — 매 source code 분석 (Semgrep, CodeQL).
|
||||
- 매 DAST (동적) — 매 runtime behavior 분석 (ZAP, Burp).
|
||||
|
||||
## 🔗 Graph
|
||||
- Adjacent: [[SAST]] · [[보안_및_시스템_신뢰성_표준|DAST]] · [[Fuzzing]]
|
||||
|
||||
## 🕓 변경 이력
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | 중복 처리 — canonical 문서로 redirect |
|
||||
Reference in New Issue
Block a user