[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -1,94 +1,206 @@
|
||||
---
|
||||
id: wiki-2026-0508-상태-머신-state-machine-모델링-및-redux-
|
||||
title: 상태 머신 (State Machine) 모델링 및 Redux 액션 리듀서 설계
|
||||
title: 상태 머신 (State Machine) 모델링 및 Redux 액션/리듀서 설계
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-Reinforce-AUTO-D423C6]
|
||||
aliases: [State Machine + Redux, FSM Redux Design, XState + Redux]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
tags: [auto-reinforced]
|
||||
verification_status: applied
|
||||
tags: [state-machine, redux, xstate, frontend, architecture]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-20
|
||||
github_commit: "[P-Reinforce] Continuous Worker - 상태 머신 ([[State|State]] Machine) 모델링 및 Redux 액션_리듀서 설계"
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: typescript
|
||||
framework: redux-toolkit
|
||||
---
|
||||
|
||||
# [[상태 머신 (State Machine) 모델링 및 Redux 액션_리듀서 설계|상태 머신 (State Machine) 모델링 및 Redux 액션_리듀서 설계]]
|
||||
# 상태 머신 (State Machine) 모델링 및 Redux 액션/리듀서 설계
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> 상태 머신(State Machine) 모델링과 Redux 액션/리듀서 설계는 애플리케이션의 복잡한 상태 전이를 명확하게 정의하고 관리하기 위한 구조적 접근법입니다. 타입스크립트(TypeScript) 환경에서는 주로 식별 가능한 유니온([[Discriminated Unions|Discriminated Unions]]) 패턴을 활용하여 이러한 상태 및 액션들을 안전하고 완벽하게 구현할 수 있습니다 [1-3]. 다만, 제공된 소스에는 이를 구체적으로 설계하는 세부 방법론이나 코드 레벨의 상세한 정보가 부족합니다.
|
||||
## 매 한 줄
|
||||
> **"매 impossible state 의 unrepresentable 화"**. 매 finite state machine (FSM) 는 explicit state + event + transition 의 enumerate. Redux reducer 는 매 (state, action) → state 의 pure function — 매 FSM 와 isomorphic. 2026 년 매 XState 5 + RTK 의 combine 패턴 의 standard.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
- **식별 가능한 유니온(Discriminated Unions)과의 시너지**: 타입스크립트의 식별 가능한 유니온 패턴은 Redux 스타일의 리듀서를 설계하거나 상태 머신을 모델링하는 데 완벽하게 부합하며 그 진가를 발휘합니다 [1, 2].
|
||||
- **상태 머신 패턴 (State Machine Pattern)의 상태와 전이**: 식별 가능한 유니온을 사용하여 상태 머신을 모델링하면 명확한 상태 전이(State transitions)를 타입으로 강제하고 표현할 수 있습니다 [3, 4]. 소스에서 언급된 상태 머신 모델링의 예시는 다음과 같습니다 [3]:
|
||||
- **상태 (States)**: `Idle` (대기), `Fetching` (가져오는 중), `Success` (성공), `Failure` (실패)
|
||||
- **액션/전이 (Actions/Transitions)**: `FETCH_START`, `FETCH_SUCCESS`, `FETCH_FAILURE`, `RETRY` (재시도 횟수가 남은 경우), `REFRESH`
|
||||
- **데이터 부족 안내**: **소스에 관련 정보가 부족합니다.** 업로드된 소스 데이터에서는 식별 가능한 유니온이 상태 머신 모델링 및 Redux 액션/리듀서 설계에 아주 적합하다는 점과 간단한 상태 목록만 언급될 뿐, 이들을 어떻게 아키텍처 관점에서 설계하고 구현해야 하는지에 대한 구체적인 설명이나 예제 코드는 포함되어 있지 않습니다.
|
||||
## 매 핵심
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
|
||||
- **정책 변화:** Design & Experience 분야의 자동 자산화 수행.
|
||||
### 매 FSM 5-tuple
|
||||
- **States (Q)**: enumerable set — `idle | loading | success | error`.
|
||||
- **Events (Σ)**: external triggers — `FETCH | RESOLVE | REJECT`.
|
||||
- **Transitions (δ)**: `Q × Σ → Q` — 매 partial function.
|
||||
- **Initial state (q₀)**: `idle`.
|
||||
- **Final states (F)**: optional — terminal nodes.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- **Related Topics:** 식별 가능한 유니온 (Discriminated Unions), [[타입 안전성 (Type Safety)|타입 안전성 (Type Safety]]
|
||||
- **Projects/Contexts:** [[React 상태 관리 (React State Management)|React 상태 관리 (React State Management]], [[비동기 데이터 패칭 (Async Operations Pattern)|비동기 데이터 패칭 (Async Operations Pattern]]
|
||||
- **Contradictions/Notes:** 소스에 관련 정보가 부족합니다. 상태 머신 및 Redux 패턴 설계 지침을 다루기보다는, 타입스크립트의 '식별 가능한 유니온'이 활용되기 좋은 대표적인 사례(Use Case) 중 하나로서만 간략히 소개되어 있습니다.
|
||||
### 매 Redux 와 mapping
|
||||
- **Reducer = δ**: `(state, action) => newState` 의 pure transition.
|
||||
- **Action = Σ event**: typed discriminated union.
|
||||
- **Store state = Q**: 매 status field 의 enum.
|
||||
- **Selector**: 매 derived view — `isLoading = state.status === 'loading'`.
|
||||
|
||||
---
|
||||
*Last updated: 2026-04-18*
|
||||
### 매 응용
|
||||
1. Form wizard — multi-step flow 의 state 의 explicit.
|
||||
2. Data fetching — idle/loading/success/error 의 4-state.
|
||||
3. Auth flow — anonymous/authenticating/authenticated/expired.
|
||||
|
||||
---
|
||||
## 💻 패턴
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
### Discriminated union state
|
||||
```typescript
|
||||
type FetchState<T> =
|
||||
| { status: 'idle' }
|
||||
| { status: 'loading' }
|
||||
| { status: 'success'; data: T }
|
||||
| { status: 'error'; error: Error };
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
// 매 impossible state ('loading' + data) 의 unrepresentable.
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### RTK slice = FSM reducer
|
||||
```typescript
|
||||
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
const userSlice = createSlice({
|
||||
name: 'user',
|
||||
initialState: { status: 'idle' } as FetchState<User>,
|
||||
reducers: {
|
||||
fetch: (state) => {
|
||||
if (state.status === 'idle' || state.status === 'error') {
|
||||
return { status: 'loading' };
|
||||
}
|
||||
return state; // ignore invalid transition
|
||||
},
|
||||
resolve: (_, action: PayloadAction<User>) => ({
|
||||
status: 'success',
|
||||
data: action.payload,
|
||||
}),
|
||||
reject: (_, action: PayloadAction<Error>) => ({
|
||||
status: 'error',
|
||||
error: action.payload,
|
||||
}),
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### Transition guard table
|
||||
```typescript
|
||||
const TRANSITIONS = {
|
||||
idle: { FETCH: 'loading' },
|
||||
loading: { RESOLVE: 'success', REJECT: 'error' },
|
||||
success: { FETCH: 'loading' },
|
||||
error: { FETCH: 'loading' },
|
||||
} as const;
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
function transition<S extends keyof typeof TRANSITIONS>(
|
||||
state: S,
|
||||
event: string
|
||||
): string {
|
||||
return (TRANSITIONS[state] as any)[event] ?? state;
|
||||
}
|
||||
```
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
### XState 5 + Redux integration
|
||||
```typescript
|
||||
import { createMachine, createActor } from 'xstate';
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
const fetchMachine = createMachine({
|
||||
id: 'fetch',
|
||||
initial: 'idle',
|
||||
states: {
|
||||
idle: { on: { FETCH: 'loading' } },
|
||||
loading: {
|
||||
invoke: {
|
||||
src: 'fetchUser',
|
||||
onDone: { target: 'success', actions: 'storeData' },
|
||||
onError: 'error',
|
||||
},
|
||||
},
|
||||
success: { on: { REFRESH: 'loading' } },
|
||||
error: { on: { RETRY: 'loading' } },
|
||||
},
|
||||
});
|
||||
|
||||
const actor = createActor(fetchMachine).start();
|
||||
actor.subscribe((snapshot) => store.dispatch({ type: 'fsm/sync', payload: snapshot.value }));
|
||||
```
|
||||
|
||||
### Hierarchical (nested) state
|
||||
```typescript
|
||||
// 매 auth flow — 매 sub-state machine.
|
||||
const authMachine = createMachine({
|
||||
initial: 'unauthenticated',
|
||||
states: {
|
||||
unauthenticated: {
|
||||
initial: 'idle',
|
||||
states: {
|
||||
idle: { on: { LOGIN: 'submitting' } },
|
||||
submitting: { on: { SUCCESS: '#auth.authenticated', FAIL: 'idle' } },
|
||||
},
|
||||
},
|
||||
authenticated: {
|
||||
on: { LOGOUT: 'unauthenticated' },
|
||||
},
|
||||
},
|
||||
}, { id: 'auth' });
|
||||
```
|
||||
|
||||
### Parallel state regions
|
||||
```typescript
|
||||
const editorMachine = createMachine({
|
||||
type: 'parallel',
|
||||
states: {
|
||||
document: { initial: 'clean', states: { clean: {}, dirty: {} } },
|
||||
network: { initial: 'online', states: { online: {}, offline: {} } },
|
||||
},
|
||||
});
|
||||
// 매 state = (document, network) 의 cross product — explicit.
|
||||
```
|
||||
|
||||
### Test as transition table
|
||||
```typescript
|
||||
test.each([
|
||||
['idle', 'FETCH', 'loading'],
|
||||
['loading', 'RESOLVE', 'success'],
|
||||
['loading', 'REJECT', 'error'],
|
||||
['success', 'FETCH', 'loading'],
|
||||
])('transition %s --%s--> %s', (from, event, to) => {
|
||||
expect(transition(from, event)).toBe(to);
|
||||
});
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Simple async (fetch) | RTK `createAsyncThunk` + discriminated union |
|
||||
| Multi-step wizard | XState machine |
|
||||
| Complex auth | XState hierarchical machine |
|
||||
| Parallel concerns | XState parallel states |
|
||||
| Pure UI toggle | useState (not Redux) |
|
||||
|
||||
**기본값**: RTK + discriminated union state. 복잡 시 XState 5.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Finite State Machine]] · [[Redux]]
|
||||
- 변형: [[XState]] · [[Statecharts]]
|
||||
- 응용: [[Form Wizard]] · [[Data Fetching]] · [[Auth Flow]]
|
||||
- Adjacent: [[Discriminated Union]] · [[Pure Function]] · [[Event Sourcing]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: state 가 3+ 개 + transition 의 explicit rule 의 필요 시.
|
||||
**언제 X**: simple boolean toggle 또는 single-shot async — 매 overkill.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Boolean explosion**: `isLoading + isError + isSuccess` — impossible state (true+true) 의 representable.
|
||||
- **Implicit transition**: reducer 안 valid state check 의 X — 매 invalid transition 의 silently 발생.
|
||||
- **God reducer**: 매 모든 logic 의 한 reducer — 매 split.
|
||||
- **Side effect in reducer**: `fetch()` 의 reducer 내부 — 매 thunk/saga/middleware 사용.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Hopcroft & Ullman *Automata Theory*; Redux docs; XState v5 docs 2026).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — FSM↔Redux mapping + XState 5 patterns |
|
||||
|
||||
Reference in New Issue
Block a user