Skip to main content

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 이상이 필요합니다.

구독

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)으로 받을 수도 있습니다.

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

발행

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

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()

와일드카드(패턴) 구독

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

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을 잡지 않습니다.

토픽 관리

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

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) 페일오버

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

qmgr.connect("10.0.0.1", 5000, "APP", True)   # 주소 하나면 됩니다
print(qmgr.get_cluster_addresses())           # ['10.0.0.1:5000', '10.0.0.2:5000']
qmgr.reconnect()                              # 새 리더를 찾아 재접속

# 첫 접속 시점의 장애까지 대비하려면 목록으로 (포트 인자 없음)
qmgr.connect("10.0.0.1:5000,10.0.0.2:5000", "APP", True)

접속에 성공하면 핸드셰이크 직후 나머지 노드 주소를 서버에서 받아 캐싱하므로 주소는 하나만 주면 됩니다. 팔로워를 지목해도 거부에 실린 리더 힌트를 따라 자동으로 리더에 붙으며, 이는 단일 주소든 목록이든 마찬가지입니다. 그때 알게 된 리더 주소는 후보 캐시에 들어가 목록으로 받은 주소와 똑같이 쓰이고, set_endpoint_cache_file() 로 경로를 지정해 뒀다면 파일에도 반영됩니다(이미 있으면 그대로 둡니다).

목록은 첫 접속 시점의 장애까지 대비할 때 씁니다 — 하나만 준 그 주소가 죽어 있으면 힌트를 줄 상대조차 없기 때문입니다.

0.4.4 변경 - 자동 재접속은 옵션이 아니라 기본 동작

캐싱된 endpoint 목록이 있으면(= 클러스터) 통신 장애로 실패한 put/get 을 페일오버 재접속 후 한 번 자동 재시도합니다. 켜고 끄는 설정은 없습니다 (set_auto_reconnect() 는 제거했습니다 — 아무 일도 하지 않는 세터를 남겨 두면 "껐는데 왜 재접속하냐"는 혼란만 생깁니다).

상황 동작
미커밋 트랜잭션 있음 예외를 올립니다. 앱이 reconnect() 후 트랜잭션을 처음부터 다시 수행
미커밋 트랜잭션 없음 (auto-commit 포함) 내부에서 재접속 후 1회 재시도
endpoint 목록 없음 (비클러스터/구엔진) 예외를 올립니다 - 갈 곳이 없습니다

재시도는 at-least-once 입니다. 서버가 처리한 뒤 응답이 유실된 시점에 재시도하면 중복 put 이 생길 수 있습니다. 재시도는 같은 msgId 로 나가므로 수신측에서 메시지 ID 로 걸러낼 수 있습니다. 미커밋 트랜잭션이 없을 때만 재시도하므로 트랜잭션 유실은 없습니다.

장애 전환(failover) 시 앱이 해야 할 일

리더가 죽으면 새 리더가 뽑힐 때까지 아무도 접속을 받지 않습니다. 실측(2노드 클러스터, 엔진 7.0.1.3341) 약 15~20초가 걸립니다. 그 사이의 재접속 시도는 정상적으로 실패하므로, 한 번 실패했다고 끝내지 말고 재시도해야 합니다.

세션 종류에 따라 앱이 할 일이 갈립니다.

세션 실패 시점에 미커밋 앱이 할 일
auto-commit 없음 아무것도 안 해도 됩니다. 그 연산을 다시 부르기만 하면 라이브러리가 재접속·재시도합니다
transacted 없음 위와 같습니다
transacted 있음 reconnect() 로 자리를 옮기고 트랜잭션을 처음부터 다시 수행해야 합니다

access_queue() 는 자동 재접속 대상이 아닙니다. 끊긴 세션에서 부르면 그대로 실패하니, 재접속에 성공한 뒤에 핸들을 다시 얻으십시오. 기존 핸들을 계속 쓰는 쪽은 스스로 복구됩니다.

(1) 트랜잭션 재수행이 필요 없는 경우 — auto-commit

import time
from ilink.qmgr import ILQmgr
from ilink.exception import ILException, ILSessionException, ILOperationException

q = ILQmgr()
q.set_endpoint_cache_file("/var/run/myapp/ilink-endpoints.txt")   # 재기동 대비(선택)
q.connect("10.0.0.1", 5000, "collector", True)                    # auto-commit
queue = q.access_queue("APP.EVENTS")                              # 핸들은 한 번만 얻는다

def publish(payload):
    """페일오버가 나도 이 함수는 그대로 둔다 - 라이브러리가 복구한다."""
    for attempt in range(1, 11):
        try:
            return queue.put(payload)          # 실패하면 내부에서 재접속 + 1회 재시도
        except ILOperationException:
            raise                              # 서버가 거절 - 재시도해도 같다
        except (ILException, ILSessionException):
            if attempt == 10:
                raise                          # 승격이 20초 넘게 안 끝났다
            time.sleep(3)                      # 리더 승격을 기다렸다가 다시

앱 코드에 reconnect() 가 없다는 점이 요지입니다. 같은 큐 핸들로 put 을 다시 부르기만 하면, 승격이 끝난 시점의 호출이 새 리더에 붙어 성공합니다(실측 20.6초에 복구).

(2) 트랜잭션 재수행이 필요한 경우 — transacted

import time
from ilink.qmgr import ILQmgr
from ilink.exception import ILException, ILSessionException, ILOperationException

MAX_RETRY = 10

def process_batch(records):
    """한 번의 트랜잭션 = 전부 커밋되거나 전부 없던 일이 된다."""
    q = ILQmgr()
    q.set_endpoint_cache_file("/var/run/myapp/ilink-endpoints.txt")
    q.connect("10.0.0.1", 5000, "billing-svc", False)      # transacted
    try:
        for attempt in range(1, MAX_RETRY + 1):
            try:
                queue = q.access_queue("APP.ORDERS")       # 재접속 뒤 핸들을 다시 얻는다
                for rec in records:
                    queue.put(rec)
                q.commit()                                 # 여기까지 와야 확정된다
                return
            except ILOperationException:
                q.rollback()                               # 서버 거절 - 재시도 무의미
                raise
            except (ILException, ILSessionException):
                if attempt == MAX_RETRY:
                    raise
                try:
                    q.reconnect()                          # 승격 전이면 여기서 또 실패한다
                except Exception:
                    time.sleep(3)                          # 기다렸다가 다음 회차에 다시
                # 루프 처음으로 -> 배치 전체를 다시 넣는다
    finally:
        q.disconnect()

읽어야 할 포인트 셋입니다.

  1. 재시도 단위는 트랜잭션 전체입니다. 실패 지점부터 이어붙이면 안 됩니다 — 앞서 넣은 것들도 커밋되지 않았으므로 함께 사라집니다(실측: 미커밋 1건 유실, 재수행 후 depth 2 정상).
  2. reconnect() 자체가 실패할 수 있습니다. 승격 전에 부르면 실패하는 게 정상이라, 루프 안에서 간격을 두고 다시 불러야 합니다(실측 2번째 시도, 16.5초에 성공).
  3. ILOperationException 과 통신 예외를 갈라 잡습니다. 전자는 서버가 판단해 거절한 것이라 재시도가 무의미하고, 후자만 재접속 대상입니다. 파이썬의 예외 클래스는 평면 구조라 ILSessionException 은 ILException 의 하위 타입이 아닙니다 — 통신 장애를 잡으려면 둘 다 적어야 합니다(자바는 모두 ILException 으로 감싸므로 하나면 됩니다).

앱이 재기동되는 경우

캐싱은 메모리에만 있으므로 프로세스가 죽으면 사라집니다. 설정에 남은 옛 리더 주소로 다시 붙을 때 이렇게 갈립니다.

옛 리더의 상태 결과
살아 있고 팔로워로 강등 그 노드가 리더 힌트를 주므로 자동으로 새 리더에 접속
죽어 있음 갈 곳이 없어 실패 — set_endpoint_cache_file() 을 쓰거나 주소를 목록으로 주십시오
q = ILQmgr()
q.set_endpoint_cache_file("/var/run/myapp/ilink-endpoints.txt")
q.connect("10.0.0.1", 5000, "APP", True)   # 이 주소가 죽어 있어도 파일 후보로 붙는다

0.4.0 신규 - 관리 연결 하나로 pub/sub

ILAdminService(관리 포트, 보통 9998) 연결만으로 토픽 발행·구독이 가능합니다. 큐 관리자 리스너 포트에 따로 붙지 않아도 되므로, 방화벽이 관리 포트만 열린 환경에서 쓸 수 있습니다.

엔진 v7.0.1 rev 3295 이상이 필요합니다.

from ilink.admin import ILAdminService
from ilink.exception import ILNoMsgException
from ilink.topic import ILSubscribeOptions, ILTopic

svc = ILAdminService()
svc.connect("127.0.0.1", 9998, "admin-app")
aq = svc.accessAdminQmgr("QM1")

# 발행 - (offset, timestamp, partition)
off, ts, part = aq.publish("ORDER.EVENT", b"payload", key="order-1")

# 구독
topic = aq.accessTopic("ORDER.EVENT")
sub = topic.subscribe("audit", ILSubscribeOptions()
                      .startMode(ILTopic.START_EARLIEST)
                      .commitMode(ILTopic.COMMIT_MANUAL))
try:
    while True:
        try:
            msg = sub.read(3000)
        except ILNoMsgException:
            break
        print(msg.get_offset(), msg.get_key(), msg.get_data_string())
        sub.commit(msg)
finally:
    sub.close()

패턴(와일드카드) 구독도 같은 연결로 됩니다.

ps = aq.accessPattern("ORDER.*").subscribe("audit")

제약: 관리 연결에는 배치가 없어 레코드 한 건에 한 번 왕복합니다. 멱등 발행도 지원되지 않습니다(acks=1 고정). 대량 처리나 중복 제거가 필요하면 리스너 포트에 ILQmgr 로 붙어 ILTopicProducer 를 쓰세요.

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

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

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 ...)도 그대로 쓸 수 있습니다.

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()이 생겼습니다.

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 779개 전부에 한국어 docstring이 붙어 있습니다. 편집기에서 함수 위에 마우스를 올리거나 help()로 파라미터 타입·기본값·허용값·예외를 바로 확인할 수 있습니다.

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

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

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

Release files for jetstream-api 0.6.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for jetstream-api 0.6.2
File Size Uploaded
jetstream_api-0.6.2.tar.gz 219.3 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for jetstream-api 0.6.2
File Interpreter ABI Platform
jetstream_api-0.6.2-py3-none-any.whl Python 3 none any Details

Total release size: 440.1 kB

Release files / jetstream_api-0.6.2.tar.gz

Download URL jetstream_api-0.6.2.tar.gz
Size 219.3 kB
Tags Source
SHA-256 checksum
How to use checksums
a3b5222dbcb78fb72a1a0eec7b21037be7609fe6b58d788667cbe8188d4b1590
BLAKE2b-256 checksum
How to use checksums
d978f288ff89d34036e38227b0aa483c402d11f989ac3aaa399b7a8fbd37ba28
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.13.4

Release files / jetstream_api-0.6.2-py3-none-any.whl

Download URL jetstream_api-0.6.2-py3-none-any.whl
Size 220.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
6f41b8f2dfec61a30c13ea44bb2bd951c19a8574bd1fb70928858e5ae1ec511a
BLAKE2b-256 checksum
How to use checksums
980396604c16b035eb7a846529df7099754b12454e3b293c67fabc826eae6460
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.13.4

Release history Release notifications | RSS feed

0.17.0

2 release files

0.16.0

2 release files

0.15.0

2 release files

0.14.0

2 release files

0.13.0

2 release files

0.12.0

2 release files

0.11.0

2 release files

0.10.0

2 release files

0.9.0

2 release files

0.8.0

2 release files

0.7.4

2 release files

0.7.3

2 release files

0.7.2

2 release files

0.7.1

2 release files

0.7.0

2 release files

0.6.11

2 release files

0.6.10

2 release files

0.6.9

2 release files

0.6.8

2 release files

0.6.7

2 release files

0.6.6

2 release files

0.6.5

2 release files

0.6.4

2 release files

0.6.3

2 release files

This release

0.6.2 This release

2 release files

0.6.1

2 release files

0.6.0

2 release files

0.5.6

2 release files

0.5.5

2 release files

0.5.4

2 release files

0.5.3

2 release files

0.5.2

2 release files

0.5.1

2 release files

0.5.0

2 release files

0.4.5

2 release files

0.4.4

2 release files

0.4.3

2 release files

0.4.2

2 release files

0.4.1

2 release files

0.4.0

2 release files

0.3.0

2 release files

0.1.6

2 release files

0.1.5

2 release files

0.1.4

2 release files

0.1.3

2 release files

0.1.2

2 release files

0.1.1

2 release files

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page