Files
llm-wiki/raw/official-docs/functional-tx-arrow-kt-resource-docs.md

122 lines
12 KiB
Markdown

---
title: "Resource Safety :: Arrow Kt Documentation"
source_type: official-doc
url: https://arrow-kt.io/learn/coroutines/resource-safety/
archive_url:
status: raw
confidence: medium
tags: [ca-transaction-boundary, functional, arrow-kt, kotlin, resource-monad, official-doc]
related_branches: [feature-application-port-usecase-contract, feature-transaction-concurrency-contract]
related_projects: [ca-skeleton]
created: 2026-05-22
last_reviewed: 2026-05-27
---
# Resource Safety — Arrow Kt 공식 문서
> Layer: `raw/official-docs/` — Arrow Kt "Resource Safety" 페이지 verbatim 발췌. ca-tmpl TransactionPort 대안 비교 자료.
## Parent / 활용 branch (필수)
| Branch | 이 자료가 정당화하는 결정 |
|---|---|
| [[raw/branch-notes/feature-application-port-usecase-contract]] | 함수형 (Effect/Resource monad) 트랜잭션 관리 가 application port 설계와 어떻게 다른지의 비교 근거 |
| [[raw/branch-notes/feature-transaction-concurrency-contract]] | TransactionPort 결정 대안 4 (Functional / Resource monad) 의 비교 자료. 채택하지 않는 이유 (stack 자체 변경 필요) 의 근거 |
## 컨텍스트 / 왜 저장했는지
ca-tmpl 의 TransactionPort 결정에 대한 대안 4: **함수형 (Effect/Resource monad) 트랜잭션 관리**. Cats Effect, Arrow Kt 진영에서 트랜잭션을 "리소스 획득-사용-해제" 스코프로 다루는 패턴. Spring AOP 에 의존하지 않는 유일한 진영.
## 출처 / Source
- 원본 URL: https://arrow-kt.io/learn/coroutines/resource-safety/
- 아카이브 URL: (미수집)
- 저자 / 조직: Arrow Kt (arrow-kt.io)
- 발행일: Arrow 1.x / 2.x current docs
- 마지막 확인일: 2026-05-27
## 핵심 인용 / Key quotes (verbatim)
**Arrow Kt "Resource Safety" — 2026-05-27 fetch 로 확인된 인용**:
> [§Understanding the problem] "The Resource DSL adds the ability to *install* resources and ensure proper finalization even in the face of exceptions and cancellations."
> [§Understanding the problem] "Arrow's Resource co-operate with Structured Concurrency and KotlinX Coroutines."
> [§Dealing with resources properly] "The `ResourceScope` DSL allows you to *install* resources and safely interact with them."
> [§Dealing with resources properly] "The result of this function is whatever was acquired, plus the promise of running the finalizer at the end of the block."
> [§Using `resourceScope`] "The Resource DSL gives you enough flexibility to perform different actions depending on how the execution finished: successful completion, exceptions, or cancellation."
> [§Using `Resource`] "The main difference is that the result is a value of type `Resource<T>`, where `T` is the type of the resource to acquire."
> [§Using `Resource`] "To actually acquire the resource, you need to call `.bind()` inside a `resourceScope`."
> [§Using `Resource`] "Although `resourceScope` provides nicer syntax in general, some usage patterns like acquiring several resources become easier when the steps are saved in an actual class."
> [§Using `Resource`] "Resource is nothing more than a type alias for parameter-less function using `ResourceScope`"
**원래 raw 수집본 (current page 와 표현 차이 — needs-confirmation)**:
> [§(과거 표현) — needs-confirmation] "Allocation and release of resources is not easy, especially when we have multiple resources that depend on each other. The Resource DSL adds the ability to *install* resources and ensure proper finalization even in the face of exceptions and cancellations." *(첫 문장 "Allocation and release..." 은 2026-05-27 fetch 에서 verbatim 미발견. 두 번째 문장은 §Understanding the problem 에 verbatim 존재)*
> [§(과거 표현) — needs-confirmation] "Arrow provides two approaches: the `resourceScope` DSL for direct resource installation with finalizers, and wrapping resource logic as `Resource<T>` values for composable recipes." *(2026-05-27 fetch 에서 verbatim 미발견 — 다만 두 패턴 (resourceScope DSL + Resource value) 의 존재는 위 verbatim 인용으로 확인됨)*
> [§(과거 표현) — needs-confirmation] "Both patterns cooperate seamlessly with Kotlin's structured concurrency model, making them functional alternatives to traditional resource management approaches." *(2026-05-27 fetch 에서 verbatim 미발견 — "Arrow's Resource co-operate with Structured Concurrency and KotlinX Coroutines." 가 동등 의미의 verbatim)*
## Claims Extracted / 추출된 주장
| Claim ID | Claim (이 자료가 직접 말하는 것) | Evidence quote | Strength | Applies to | Does not prove |
|---|---|---|---|---|---|
| ARROW-RES-C1 | Resource DSL 은 resource 를 install 하고, exception 및 cancellation 상황에서도 적절한 finalization 을 보장 | [§Understanding the problem] "The Resource DSL adds the ability to *install* resources and ensure proper finalization even in the face of exceptions and cancellations." | `official-vendor-doc` | Arrow Kt `Resource` API 사용 | "JDBC connection / DB transaction 에 1:1 매핑되는 표준 어댑터" 의 존재는 본 인용 범위 밖 — 사용자가 직접 acquire/release 정의 필요 |
| ARROW-RES-C2 | Arrow 의 Resource 는 Kotlin Structured Concurrency + KotlinX Coroutines 와 협력 | [§Understanding the problem] "Arrow's Resource co-operate with Structured Concurrency and KotlinX Coroutines." | `official-vendor-doc` | Kotlin coroutines 환경 | Java thread / Project Loom virtual thread 와의 호환성은 본 인용 범위 밖 |
| ARROW-RES-C3 | `ResourceScope` DSL 은 resource 를 install 하고 안전하게 상호작용 가능 | [§Dealing with resources properly] "The `ResourceScope` DSL allows you to *install* resources and safely interact with them." | `official-vendor-doc` | `ResourceScope` 사용 | DSL 의 정확한 신택스 (e.g., `install` 함수 시그니처) 는 본 인용 범위 밖 |
| ARROW-RES-C4 | install 함수의 결과는 acquire 된 값 + block 끝에서 finalizer 실행 보장 | [§Dealing with resources properly] "The result of this function is whatever was acquired, plus the promise of running the finalizer at the end of the block." | `official-vendor-doc` | install 함수 호출 | "block 끝" 의 정확한 의미 (suspend 종료 / exception 던짐 / cancellation 등 분기) 는 §Using resourceScope 의 추가 인용으로 보강 |
| ARROW-RES-C5 | Resource DSL 은 execution 종료 방식 (성공 / exception / cancellation) 에 따라 다른 action 수행이 가능한 유연성 제공 | [§Using `resourceScope`] "The Resource DSL gives you enough flexibility to perform different actions depending on how the execution finished: successful completion, exceptions, or cancellation." | `official-vendor-doc` | finalizer 분기 처리 결정 | 구체적 분기 API (`onSuccess` / `onError` / `onCancel` 등) 는 본 인용 범위 밖 |
| ARROW-RES-C6 | `Resource<T>` 는 type T 의 resource 를 acquire 하는 value. `resourceScope` 안에서 `.bind()` 로 실제 acquire | [§Using `Resource`] "The main difference is that the result is a value of type `Resource<T>`, where `T` is the type of the resource to acquire." / "To actually acquire the resource, you need to call `.bind()` inside a `resourceScope`." | `official-vendor-doc` | `Resource<T>` value 합성 사용 | bind 호출의 fail 동작 (예외 전파 vs Either 변환) 은 본 인용 범위 밖 |
| ARROW-RES-C7 | `resourceScope` 가 일반적으로 더 깔끔하지만, 여러 resource 를 acquire 하는 패턴은 class 에 step 을 저장하는 것이 더 쉬움 | [§Using `Resource`] "Although `resourceScope` provides nicer syntax in general, some usage patterns like acquiring several resources become easier when the steps are saved in an actual class." | `official-vendor-doc` | 다중 resource composition 결정 | "어떤 임계값에서 class 패턴이 우월한지" 의 정량적 가이드는 본 인용 범위 밖 |
| ARROW-RES-C8 | Resource 는 `ResourceScope` 를 사용하는 parameter-less function 의 type alias | [§Using `Resource`] "Resource is nothing more than a type alias for parameter-less function using `ResourceScope`" | `official-vendor-doc` | Resource 의 내부 구현 이해 | 이 정의가 backward compatibility 보장된다는 의미는 아님 |
## Usage Boundaries / 적용 경계
- **이 자료가 직접 증명하는 것**:
- `ARROW-RES-C1~C8`: Arrow `Resource` / `ResourceScope` DSL 의 의도된 동작 (install / finalization / structured concurrency 협력 / 분기 처리 / value 합성 / class 패턴 trade-off)
- **이 자료가 증명하지 않는 것**:
- DB transaction (commit/rollback) 과 `Resource` 의 1:1 매핑 — 본 페이지는 일반 resource 관리만 다룸. 트랜잭션 매핑은 사용자가 직접 정의해야 함
- Spring Data / JPA EntityManager 와의 호환성 — 본 페이지 범위 밖 (해석 메모 영역)
- "함수형 트랜잭션 관리가 Spring AOP 보다 우월하다" — 본 인용은 capability 만 제공
- 원 raw 의 첫 두 verbatim 인용 ("Allocation and release..." / "Arrow provides two approaches...") 의 정확한 출처 — 2026-05-27 fetch 에서 verbatim 미발견. 과거 버전 문서의 표현 가능성
- **내 프로젝트에 적용하려면 추가 확인이 필요한 것**:
- JDBC connection 을 `Resource<Connection>` 으로 감싸는 표준 구현체 / 라이브러리 존재 여부
- r2dbc / Exposed / jOOQ 와의 통합 모듈 존재 여부
- Arrow 0.x → 1.x → 2.x 의 `Resource` 시그니처 변경 정도 (migration 비용)
- **company tech blog 사례를 "Arrow 공식 best practice" 로 일반화 금지** — 본 raw 는 공식 docs 의 일반 resource API 만 다룸
## 메모 / Notes (내 프로젝트 해석 — PRESERVED)
> 본 섹션은 자료 직접 인용 아님. ca-tmpl 결정 컨텍스트 해석.
- 적용 시나리오: Kotlin/Scala FP 진영. JDBC connection 을 `Resource` 로 감싸 acquire-commit/rollback-close 흐름을 만들거나, 도메인 함수가 `Either<DomainError, A>` / `suspend` 시그니처를 일관되게 가지는 코드베이스.
- 장점:
- 트랜잭션 경계가 타입 시그니처에 드러남 (`suspend ResourceScope.() -> A`, `Either<E, A>`). 컴파일러로 강제 가능.
- Spring / JPA / AOP 의존 0. 순수 라이브러리.
- 비즈니스 오류 (`Left`) 는 자동 rollback, 성공 (`Right`) 은 commit 같은 규칙을 한 위치에서 표현 가능 (해석 — 본 자료 직접 증명 아님).
- 단점:
- JVM 백엔드 주류와 거리 큼. 팀 학습 곡선·채용 풀 좁아짐.
- Spring Data / JPA EntityManager 는 본질적으로 mutable + ThreadLocal 기반이라 Arrow 의 functional 모델과 마찰. r2dbc + jOOQ 등으로 옮기는 게 자연스러움.
- 라이브러리 자체 변경 속도 빠름 (0.x → 1.x → 2.x 시그니처 변경 다수).
- ca-tmpl (TransactionPort) 와의 차이: ca-tmpl 은 OOP port-adapter 로 Spring 을 숨기는 데 그치지만, Arrow 는 **함수 시그니처 수준** 에서 트랜잭션 경계를 표현. 더 강한 분리지만 stack 자체 변경 필요.
- testability 영향: ★★ — 순수 함수와 `Resource` 합성. context 부팅 없이 검증 가능.
- code 복잡도 영향: 높음 — FP 스타일 전면 도입 가정. 팀 전체가 함께 가지 않으면 비용 폭증.
## Related / 관련
- 인용하는 branch:
- [[raw/branch-notes/feature-application-port-usecase-contract]]
- [[raw/branch-notes/feature-transaction-concurrency-contract]]
- 적용 contract:
- [[raw/project-notes/ca-skeleton-operational-contract]] (Transaction / Concurrency 그룹, Exception Ownership 그룹)
- 대안 그룹 — **Topic 2 Transaction Boundary** 5종: TransactionPort / `@Transactional` direct / TransactionTemplate / Functional monad (본 자료) / Custom AOP
- 인용하는 wiki: (미작성)