Metadata-Version: 2.4
Name: jetstream-api
Version: 0.3.0
Summary: Python client API for iLink M.O.M. (Message Oriented Middleware)
Author: snowjeans
License: Boost Software License - Version 1.0 - August 17th, 2003
        
        Permission is hereby granted, free of charge, to any person or organization
        obtaining a copy of the software and accompanying documentation covered by
        this license (the "Software") to use, reproduce, display, distribute,
        execute, and transmit the Software, and to prepare derivative works of the
        Software, and to permit third-parties to whom the Software is furnished to
        do so, all subject to the following:
        
        The copyright notices in the Software and this entire statement, including
        the above license grant, this restriction and the following disclaimer,
        must be included in all copies of the Software, in whole or in part, and
        all derivative works of the Software, unless such copies or derivative
        works are solely in the form of machine-executable object code generated by
        a source language processor.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
        SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
        FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
        ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
        DEALINGS IN THE SOFTWARE.
        
Keywords: ilink,mom,messaging,middleware,queue,jetstream
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: License :: OSI Approved :: Boost Software License 1.0 (BSL-1.0)
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: System :: Networking
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE.txt
Provides-Extra: test
Requires-Dist: docstring_parser>=0.16; extra == "test"
Dynamic: license-file

﻿# jetstream-api

Python으로 작성된 ILink 클라이언트 API입니다.

## 시스템 요구 사항
시스템에 python 13 이상, pip가 설치되어 있어야 합니다.

## 설치 방법
pip install jetstream-api

## 0.2.0 신규 - pub/sub 토픽

큐에 더해 **pub/sub 토픽**을 지원합니다. 발행된 메시지는 retention 정책이 지울 때까지 보존되어
모든 구독자에게 각자의 커서로 전달됩니다(팬아웃). 큐와 달리 소비해도 사라지지 않습니다.

> 엔진 v7.1.1 rev 3265 이상이 필요합니다.

### 구독

```python
from ilink.qmgr import ILQmgr
from ilink.topic import ILTopic, ILSubscribeOptions

qmgr = ILQmgr()
qmgr.connect("127.0.0.1", 19999, "order-svc", True)

topic = qmgr.access_topic("ORDER.EVENT")
sub = topic.subscribe("settlement", ILSubscribeOptions()
                      .start_mode(ILTopic.START_EARLIEST)
                      .commit_mode(ILTopic.COMMIT_MANUAL))

for msg in sub.read_batch(100, 3000):
    print(msg.get_offset(), msg.get_key(), msg.get_data_string())
    sub.commit(msg)
```

콜백(push)으로 받을 수도 있습니다.

```python
sub.listen(lambda m: print(m.get_data_string()),
           lambda e: print("error:", e))
...
sub.stop_listening()
```

### 발행

발행은 producer 단일 경로입니다. 동기 발행은 `send().get()`을 씁니다.

```python
from ilink.producer import ILProducerConfig, ILProducerRecord

prod = qmgr.create_producer(ILProducerConfig())
meta = prod.send(ILProducerRecord("ORDER.EVENT", "k1", b"payload",
                                  properties={"trace-id": "abc"})).get()
print(meta.get_partition(), meta.get_offset())
prod.close()
```

### 와일드카드(패턴) 구독

패턴에 맞는 여러 토픽을 한꺼번에 구독합니다.

```python
pat = qmgr.access_pattern("ORDER.*")
print(pat.resolve())                    # 지금 매칭되는 토픽 (구독 안 함)

ps = pat.subscribe("audit")
m = ps.read(3000)
print(m.get_topic_name(), m.get_data_string())
```

**`*`는 구분자 `.`를 포함해 매칭합니다.** `ORDER.*`는 `ORDER.KR`뿐 아니라 `ORDER.KR.SUB`도 잡습니다.
**정규식이 아니라 글로브입니다.** `.`은 리터럴이라 `ORDER.*`는 `ORDERING`을 잡지 않습니다.

### 토픽 관리

토픽 생성/삭제/속성변경은 관리 표면 전용입니다.

```python
from ilink.admin import ILAdminService

svc = ILAdminService(); svc.connect("127.0.0.1", 9998)
adm = svc.accessAdminQmgr("QMGR1")
adm.createTopic("ORDER.EVENT", "partitions=3")
print(adm.getTopicList())
```

## 0.2.0 신규 - 클러스터(HA) 페일오버

클러스터 큐 관리자에 접속하면 후보 주소를 캐싱해 두었다가, 리더가 바뀌어도 따라갑니다.

```python
qmgr.set_auto_reconnect(True)     # auto-commit 세션에서만 동작
print(qmgr.get_cluster_addresses())
qmgr.reconnect()                  # 새 리더를 찾아 재접속
```

> `set_auto_reconnect`는 **transacted 세션에서는 동작하지 않습니다.** 미커밋 트랜잭션이
> 재접속으로 유실되므로, 예외를 받고 앱이 트랜잭션을 처음부터 재수행해야 합니다
> (`reconnect()` 직접 호출은 가능합니다). auto-commit 세션도 응답 유실 시점의 재시도로
> **중복 put이 발생할 수 있습니다.**

## 0.3.0 신규 - 허브-스포크 연결 전환 헬퍼

허브에 접속해 스포크를 찾고 연결을 전환하는 세 단계를 한 번에 처리하는
`connectToSpoke()`가 추가되었습니다. Java API에도 같은 이름으로 있습니다.

```python
from ilink.admin import ILAdminService

for name in ("S48", "S85"):
    svc = ILAdminService.connectToSpoke("10.10.1.95", 9998, "ADMIN", name)
    try:
        print(name, [q.getName() for q in svc.getQmgrList()])
    finally:
        svc.disconnect()

# 키를 이미 알고 있으면 목록 조회를 건너뛴다 (키는 설정 파일에 저장되어 재기동해도 유지)
svc = ILAdminService.connectToSpokeByKey("10.10.1.95", 9998, "ADMIN", spoke_key)
```

> 연결 전환 후 그 연결은 **해당 스포크에 직접 접속한 것으로 에뮬레이션**됩니다.
> 따라서 전환은 연결당 한 번뿐이고, 다른 스포크로 가려면 새 연결이 필요합니다.
> `connectToSpoke()`가 그 반복을 담당합니다. 실패하면 스스로 연결을 닫으므로
> 소켓이 새지 않습니다.

TCP 연결 방향이 **스포크 → 허브** 한 방향뿐이라 스포크 쪽에 인바운드 포트를 열지 않고도
관리할 수 있습니다. 실측상 릴레이 오버헤드는 없었습니다(`getQmgrList()` 중앙값
릴레이 18.3ms vs 허브 직결 18.4ms).

## 0.2.1 신규 - Java API 옵션 표면 일치

발행/구독 옵션이 Java API와 **같은 이름의 빌더**로 정리되었습니다. 기존 snake 표기
(`start_mode` / `commit_mode` / `linger_ms` ...)도 그대로 쓸 수 있습니다.

```python
from ilink.producer import ILProducerConfig

cfg = (ILProducerConfig()
       .acks(1).lingerMs(5).batchSize(32768)
       .maxRequestSize(1048576)      # 레코드 1건 상한 - 넘으면 send()가 거부
       .bufferMemory(33554432)       # 미전송 누적 상한
       .retries(3).retryBackoffMs(100)
       .deliveryTimeoutMs(120000)    # 재시도를 포함한 완결 시한
       .enableIdempotence(True))     # PID/시퀀스 중복 제거 (acks=1 필요)

prod = qmgr.create_producer(cfg)
print(prod.get_producer_id(), prod.is_connected())
```

구독 옵션에 리밸런스 리스너/prefetch/수동 파티션이 추가되었고, 파티션을 직접 고르는
`assign()`이 생겼습니다.

```python
sub = topic.subscribe("app1", ILSubscribeOptions()
                      .startMode(ILTopic.START_EARLIEST)
                      .commitMode(ILTopic.COMMIT_MANUAL)
                      .expiryMs(600000)          # 멤버 유휴 만료 10분
                      .prefetch(100)
                      .listener(on_rebalance))

sub = topic.assign("app1", [0, 2], ILTopic.START_EARLIEST)   # 수동 파티션 배정
```

> **주의 (0.2.0에서 올라올 때)**: 옵션 값은 이제 **게터로 읽습니다.**
> `cfg.acks` / `opt.durable` 은 빌더 **메서드**이므로 값이 필요하면
> `cfg.get_acks()` / `opt.is_durable()` 을 쓰세요. `cfg.acks = 0` 같은 **직접 대입은
> 그대로 동작합니다.** 같은 이유로 `ILClusterProperty.isAutoStart` 와
> `ILSpokeProperty.isRunning` 도 Java처럼 **메서드**가 되었습니다
> (`prop.isAutoStart()`).

## 개발자 가이드 문서

**공개 API 756개 전부에 한국어 docstring이 붙어 있습니다.** 편집기에서 함수 위에
마우스를 올리거나 `help()`로 파라미터 타입·기본값·허용값·예외를 바로 확인할 수 있습니다.

```python
help(qmgr.access_queue)
help(ILAdminQmgr.getStatSeries)
```

값 객체(`ILQueueProperty` 등)는 필드 목록이 클래스 docstring에 정리되어 있습니다.
`getX()` / `setX()` 접근자는 필드 이름에서 자동으로 만들어지므로, 필드 목록이 곧
접근자 목록입니다.

```python
help(ILQueueProperty)      # 필드 이름 / 타입 / 기본값 / 의미
```
