Files
2nd/10_Wiki/Topic_Programming/Architecture/Cross-Cutting Concerns.md
T
Antigravity Agent 9148c358d0 docs(10_Wiki): 위키 전체 재구성 — Topic_* 폴더를 4개 카테고리로 통합 + 대규모 중복 제거
Topic_Agent/Topic_Blog/Topics/Topics_Biz/Topics_Meeting/Topics_Rag의 마크다운 지식 문서를
Topic_General/Topic_Programming/Topic_Graphic/Topic_Business 4개 카테고리로 재분류.

- 중복 제거: frontmatter의 status:duplicate/merged + duplicate_of/redirect_to 필드로
  자기 자신을 중복으로 선언한 리다이렉트 stub 1032개 제거, 완전 동일 내용 파일 472개 제거,
  동일 파일명·다른 내용 충돌 시 더 큰(완전한) 버전만 유지(162개 제거) — 총 1639개 중복 제거.
- 분류: 폴더 단위로 명확한 항목(AI_and_ML/Coding/Architecture 등 → Programming,
  Comfyui/Visual_Effects → Graphic, Topics_Biz/Topics_Meeting/사업 등 → Business,
  Poetic_Blog_Writing/창의성/Game_Design 등 → General)은 폴더 우선순위로,
  나머지 혼재 폴더(Topic_Agent/Topic_Blog/Topics 루트/Thinking & Reasoning/Other/UI_UX_Assets)는
  title/tags 키워드 스코어링으로 파일 단위 분류(불명확한 경우 General로 폴백).
  원본 폴더명은 "From_*" 서브폴더로 보존해 추적 가능성 유지.
- 최종 배치: Programming 2784 / General 1608 / Graphic 285 / Business 249 = 4926개 문서.
- 에이전트 운영 상태(.astra/.agent/.obsidian/sessions/memory/_company/docs/lessons/_shared/src)는
  지식 콘텐츠가 아니므로 재분류 대상에서 제외하고 원위치 유지.
- Topics/Topic_email(상위 보호 폴더 Topic_email과 파일명 100% 중복) 삭제 — 보호 폴더 자체는 미변경.
- 완전히 비게 된 Topic_Agent/Topic_Blog/Topics_Biz/Topics_Rag 폴더 제거.
2026-07-05 00:33:48 +09:00

5.3 KiB

id, title, category, status, canonical_id, aliases, duplicate_of, source_trust_level, confidence_score, verification_status, tags, raw_sources, last_reinforced, github_commit, tech_stack
id title category status canonical_id aliases duplicate_of source_trust_level confidence_score verification_status tags raw_sources last_reinforced github_commit tech_stack
wiki-2026-0508-cross-cutting-concerns Cross-Cutting Concerns 10_Wiki/Topics verified self
Cross Cutting Concerns
AOP Concerns
횡단 관심사
none A 0.9 applied
aop
architecture
separation-of-concerns
2026-05-10 pending
language framework
typescript nestjs

Cross-Cutting Concerns

매 한 줄

"매 module 매 흩어지는 functionality (logging, auth, tx) 의 횡단". AOP (Aspect-Oriented Programming, Kiczales 1997) 의 motivation. 2026 현재 NestJS interceptors, Spring AOP, OpenTelemetry auto-instrumentation, Sidecar (Istio) 매 modern realization.

매 핵심

매 정의

  • 단일 module 의 boundary 를 넘어 매 application 매 widely-scattered concern.
  • Tangled with business logic → SoC (Separation of Concerns) 위반.
  • Solution: 매 aspect, decorator, middleware, sidecar, interceptor 로 추출.

매 typical concerns

  • Logging / tracing — 매 method entry/exit log.
  • Authentication / authorization — 매 endpoint 매 token check.
  • Transaction management — DB tx begin/commit/rollback.
  • Caching — function result memoization.
  • Validation — input schema check.
  • Rate limiting — request throttling.
  • Metrics / observability — counter, histogram.
  • Error handling — global exception mapper.
  • i18n — locale-aware response.
  • Audit — who/when/what.

매 응용

  1. Web framework middleware (Express, NestJS).
  2. Spring @Transactional / @Cacheable.
  3. Service mesh (Istio) — mTLS, retry, circuit-break 매 sidecar.
  4. OpenTelemetry auto-instrumentation 매 tracing 매 zero code change.

💻 패턴

NestJS interceptor — logging + timing

@Injectable()
export class LoggingInterceptor implements NestInterceptor {
  intercept(ctx: ExecutionContext, next: CallHandler) {
    const start = Date.now();
    const req = ctx.switchToHttp().getRequest();
    return next.handle().pipe(
      tap(() => log.info({ url: req.url, ms: Date.now() - start }))
    );
  }
}

NestJS guard — authz

@Injectable()
export class RolesGuard implements CanActivate {
  canActivate(ctx: ExecutionContext): boolean {
    const required = Reflect.getMetadata('roles', ctx.getHandler());
    const user = ctx.switchToHttp().getRequest().user;
    return required.some(r => user.roles.includes(r));
  }
}

Spring AOP — @Transactional

@Service
public class OrderService {
    @Transactional
    public Order place(Order o) {
        repository.save(o);
        inventory.decrement(o.itemId);
        // throw → rollback
    }
}

Python decorator — caching

from functools import lru_cache

@lru_cache(maxsize=1024)
def expensive_lookup(key: str) -> Result:
    return db.query(key)

TypeScript decorator (TC39 stage 3) — metrics

function timed<This, Args extends any[], Return>(
  target: (this: This, ...args: Args) => Return,
  ctx: ClassMethodDecoratorContext
) {
  return function (this: This, ...args: Args): Return {
    const start = performance.now();
    try { return target.apply(this, args); }
    finally { metrics.histogram(ctx.name, performance.now() - start); }
  };
}

class API {
  @timed
  fetchUser(id: string) { /* ... */ }
}

OpenTelemetry — zero-code tracing

# auto-instrumentation, no code changes
# pip install opentelemetry-distro opentelemetry-instrumentation-fastapi
# opentelemetry-instrument --traces_exporter otlp uvicorn app:app

Service mesh (Istio) — mTLS via sidecar

apiVersion: security.istio.io/v1
kind: PeerAuthentication
metadata: { name: default, namespace: prod }
spec:
  mtls: { mode: STRICT }

매 결정 기준

상황 Approach
Single service, JS/TS NestJS interceptor / Express middleware
JVM, mature DI Spring AOP / aspectj
Polyglot microservices Service mesh (Istio / Linkerd)
Tracing only OpenTelemetry auto-instrumentation
Function-level caching language-native decorator

기본값: framework-native (interceptor/middleware/decorator) for in-process; service mesh for network-level.

🔗 Graph

🤖 LLM 활용

언제: identify cross-cutting concern in legacy code, refactor to aspect/middleware. 언제 X: design-time SoC decision (need human architectural taste).

안티패턴

  • Concern duplication: 매 controller 매 try/catch + log + auth 매 copy-paste.
  • Aspect overuse: business logic 까지 aspect 로 → magic, debugging hell.
  • Order dependency 무시: interceptor chain 의 순서 의존 → fragile.
  • Side-effect in interceptor: DB write 매 logging interceptor → tx boundary 깨짐.

🧪 검증 / 중복

  • Verified (Kiczales et al. 1997 AOP, Spring/NestJS docs 2026).
  • 신뢰도 A.

🕓 Changelog

날짜 변경
2026-05-08 Phase 1
2026-05-10 Manual cleanup — full content covering interceptors, decorators, service mesh