@simplysm/service-client 14.0.47 → 14.0.49
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +200 -0
- package/dist/protocol/client-protocol-wrapper.d.ts.map +1 -1
- package/dist/protocol/client-protocol-wrapper.js +94 -51
- package/dist/protocol/client-protocol-wrapper.js.map +1 -1
- package/dist/types/browser-compat.d.ts +12 -1
- package/dist/types/browser-compat.d.ts.map +1 -1
- package/dist/types/browser-compat.js +11 -2
- package/dist/types/browser-compat.js.map +1 -1
- package/dist/workers/client-protocol.worker.js +33 -22
- package/dist/workers/client-protocol.worker.js.map +1 -1
- package/docs/features.md +217 -0
- package/docs/main.md +148 -0
- package/docs/protocol.md +56 -0
- package/docs/transport.md +131 -0
- package/docs/types.md +93 -0
- package/package.json +6 -5
- package/src/protocol/client-protocol-wrapper.ts +125 -68
- package/src/types/browser-compat.ts +24 -2
- package/src/types/node-worker-compat.d.ts +23 -0
- package/src/workers/client-protocol.worker.ts +39 -27
package/docs/features.md
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
# Features
|
|
2
|
+
|
|
3
|
+
## `ClientEventProxy`
|
|
4
|
+
|
|
5
|
+
`getEvent()`가 반환하는 이벤트 프록시 인터페이스. 이벤트 이름과 제네릭 타입이 캡처되어 있어 호출 시 반복 지정이 불필요하다.
|
|
6
|
+
|
|
7
|
+
```typescript
|
|
8
|
+
export interface ClientEventProxy<TEventDef extends ServiceEventDef> {
|
|
9
|
+
addListener(
|
|
10
|
+
info: TEventDef["$info"],
|
|
11
|
+
cb: (data: TEventDef["$data"]) => PromiseLike<void>,
|
|
12
|
+
): Promise<string>;
|
|
13
|
+
removeListener(key: string): Promise<void>;
|
|
14
|
+
emit(
|
|
15
|
+
infoSelector: (item: TEventDef["$info"]) => boolean,
|
|
16
|
+
data: TEventDef["$data"],
|
|
17
|
+
): Promise<void>;
|
|
18
|
+
}
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
| Member | Type | Description |
|
|
22
|
+
|--------|------|-------------|
|
|
23
|
+
| `addListener(info, cb)` | `Promise<string>` | 이벤트 리스너 등록. 반환값은 `key` (제거 시 사용) |
|
|
24
|
+
| `removeListener(key)` | `Promise<void>` | 등록된 이벤트 리스너 제거 |
|
|
25
|
+
| `emit(infoSelector, data)` | `Promise<void>` | `infoSelector`가 참인 대상에게 데이터 발행 |
|
|
26
|
+
|
|
27
|
+
## `EventClient`
|
|
28
|
+
|
|
29
|
+
서버 이벤트 구독/발행 인터페이스. 재연결 시 자동 재구독된다.
|
|
30
|
+
|
|
31
|
+
```typescript
|
|
32
|
+
export interface EventClient {
|
|
33
|
+
getEvent<TEventDef extends ServiceEventDef>(
|
|
34
|
+
eventName: string,
|
|
35
|
+
): ClientEventProxy<TEventDef>;
|
|
36
|
+
addListener<TEventDef extends ServiceEventDef>(
|
|
37
|
+
eventName: string,
|
|
38
|
+
info: TEventDef["$info"],
|
|
39
|
+
cb: (data: TEventDef["$data"]) => PromiseLike<void>,
|
|
40
|
+
): Promise<string>;
|
|
41
|
+
removeListener(key: string): Promise<void>;
|
|
42
|
+
emit<TEventDef extends ServiceEventDef>(
|
|
43
|
+
eventName: string,
|
|
44
|
+
infoSelector: (item: TEventDef["$info"]) => boolean,
|
|
45
|
+
data: TEventDef["$data"],
|
|
46
|
+
): Promise<void>;
|
|
47
|
+
resubscribeAll(): Promise<void>;
|
|
48
|
+
}
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
| Member | Type | Description |
|
|
52
|
+
|--------|------|-------------|
|
|
53
|
+
| `getEvent(eventName)` | `ClientEventProxy<TEventDef>` | 이벤트 이름과 타입을 캡처한 프록시 반환. `getService()` 패턴과 동일 |
|
|
54
|
+
| `addListener(eventName, info, cb)` | `Promise<string>` | 이벤트 리스너 등록. 제네릭 `TEventDef`로 `info`/`data` 타입 추론. 반환값은 `key` (제거 시 사용) |
|
|
55
|
+
| `removeListener(key)` | `Promise<void>` | 등록된 이벤트 리스너 제거 |
|
|
56
|
+
| `emit(eventName, infoSelector, data)` | `Promise<void>` | 서버의 이벤트 리스너 중 `infoSelector`가 참인 대상에게 데이터 발행. 제네릭 `TEventDef`로 타입 안전성 보장 |
|
|
57
|
+
| `resubscribeAll()` | `Promise<void>` | 재연결 시 모든 리스너를 서버에 재등록. `ServiceClient`가 자동 호출 |
|
|
58
|
+
|
|
59
|
+
## `createEventClient`
|
|
60
|
+
|
|
61
|
+
`EventClient` 팩토리 함수.
|
|
62
|
+
|
|
63
|
+
```typescript
|
|
64
|
+
export function createEventClient(transport: ServiceTransport): EventClient;
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
| Parameter | Type | Description |
|
|
68
|
+
|-----------|------|-------------|
|
|
69
|
+
| `transport` | `ServiceTransport` | 서비스 전송 계층 |
|
|
70
|
+
|
|
71
|
+
## `FileClient`
|
|
72
|
+
|
|
73
|
+
파일 업로드(POST)/다운로드(GET) 인터페이스.
|
|
74
|
+
|
|
75
|
+
```typescript
|
|
76
|
+
export interface FileClient {
|
|
77
|
+
download(relPath: string): Promise<Bytes>;
|
|
78
|
+
upload(
|
|
79
|
+
files: File[] | FileCollection | { name: string; data: BlobInput }[],
|
|
80
|
+
authToken: string,
|
|
81
|
+
): Promise<ServiceUploadResult[]>;
|
|
82
|
+
}
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
| Member | Type | Description |
|
|
86
|
+
|--------|------|-------------|
|
|
87
|
+
| `download(relPath)` | `Promise<Bytes>` | `GET {hostUrl}{relPath}`로 파일 다운로드. `Uint8Array` 반환 |
|
|
88
|
+
| `upload(files, authToken)` | `Promise<ServiceUploadResult[]>` | `POST {hostUrl}/upload`로 파일 업로드. `multipart/form-data` 사용 |
|
|
89
|
+
|
|
90
|
+
`upload` 파라미터:
|
|
91
|
+
|
|
92
|
+
| Parameter | Type | Description |
|
|
93
|
+
|-----------|------|-------------|
|
|
94
|
+
| `files` | `File[] \| FileCollection \| { name: string; data: BlobInput }[]` | 업로드할 파일 목록 |
|
|
95
|
+
| `authToken` | `string` | 인증 토큰 (`Authorization: Bearer {token}` 헤더로 전송) |
|
|
96
|
+
|
|
97
|
+
## `createFileClient`
|
|
98
|
+
|
|
99
|
+
`FileClient` 팩토리 함수.
|
|
100
|
+
|
|
101
|
+
```typescript
|
|
102
|
+
export function createFileClient(hostUrl: string, clientName: string): FileClient;
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
| Parameter | Type | Description |
|
|
106
|
+
|-----------|------|-------------|
|
|
107
|
+
| `hostUrl` | `string` | 서버 기본 URL (`http://host:port` 형식) |
|
|
108
|
+
| `clientName` | `string` | 클라이언트 식별자 (`x-sd-client-name` 헤더로 전송) |
|
|
109
|
+
|
|
110
|
+
## `OrmConnectOptions`
|
|
111
|
+
|
|
112
|
+
ORM 원격 연결에 필요한 옵션 인터페이스.
|
|
113
|
+
|
|
114
|
+
```typescript
|
|
115
|
+
export interface OrmConnectOptions<T extends DbContext> {
|
|
116
|
+
DbClass: new (executor: DbContextExecutor, opt: { database: string; schema?: string }) => T;
|
|
117
|
+
connOpt: DbConnOptions & { configName: string };
|
|
118
|
+
dbContextOpt?: {
|
|
119
|
+
database: string;
|
|
120
|
+
schema: string;
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
| Field | Type | Description |
|
|
126
|
+
|-------|------|-------------|
|
|
127
|
+
| `DbClass` | `new (...) => T` | 사용할 `DbContext` 서브클래스 생성자 |
|
|
128
|
+
| `connOpt` | `DbConnOptions & { configName: string }` | DB 연결 옵션. `configName`은 서버 설정 키 |
|
|
129
|
+
| `dbContextOpt` | `{ database: string; schema: string }?` | DB 컨텍스트 옵션. 생략하면 서버에서 조회한 `info.database`/`info.schema` 사용 |
|
|
130
|
+
|
|
131
|
+
## `OrmClientConnector`
|
|
132
|
+
|
|
133
|
+
`DbContext` 트랜잭션 연결을 원격 서버에서 실행하는 헬퍼 인터페이스.
|
|
134
|
+
|
|
135
|
+
```typescript
|
|
136
|
+
export interface OrmClientConnector {
|
|
137
|
+
connect<T extends DbContext, R>(
|
|
138
|
+
config: OrmConnectOptions<T>,
|
|
139
|
+
callback: (db: T) => Promise<R> | R,
|
|
140
|
+
): Promise<R>;
|
|
141
|
+
connectWithoutTransaction<T extends DbContext, R>(
|
|
142
|
+
config: OrmConnectOptions<T>,
|
|
143
|
+
callback: (db: T) => Promise<R> | R,
|
|
144
|
+
): Promise<R>;
|
|
145
|
+
}
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
| Member | Type | Description |
|
|
149
|
+
|--------|------|-------------|
|
|
150
|
+
| `connect(config, callback)` | `Promise<R>` | 트랜잭션 모드로 연결. FK 제약 위반 시 사용자 친화적 에러 메시지로 변환 |
|
|
151
|
+
| `connectWithoutTransaction(config, callback)` | `Promise<R>` | 트랜잭션 없이 연결 |
|
|
152
|
+
|
|
153
|
+
## `createOrmClientConnector`
|
|
154
|
+
|
|
155
|
+
`OrmClientConnector` 팩토리 함수.
|
|
156
|
+
|
|
157
|
+
```typescript
|
|
158
|
+
export function createOrmClientConnector(serviceClient: ServiceClient): OrmClientConnector;
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
| Parameter | Type | Description |
|
|
162
|
+
|-----------|------|-------------|
|
|
163
|
+
| `serviceClient` | `ServiceClient` | 이미 연결된 서비스 클라이언트 |
|
|
164
|
+
|
|
165
|
+
사용 예:
|
|
166
|
+
|
|
167
|
+
```typescript
|
|
168
|
+
const connector = createOrmClientConnector(client);
|
|
169
|
+
|
|
170
|
+
const result = await connector.connect(
|
|
171
|
+
{ DbClass: MyDbContext, connOpt: { configName: "main" } },
|
|
172
|
+
async (db) => {
|
|
173
|
+
return db.myTable.select((item) => ({ id: item.id, name: item.name }));
|
|
174
|
+
},
|
|
175
|
+
);
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
## `OrmClientDbContextExecutor`
|
|
179
|
+
|
|
180
|
+
`DbContextExecutor` 인터페이스 구현체. `DbContext`의 쿼리 실행을 서버 `OrmService`에 원격 호출한다. 직접 사용보다 `createOrmClientConnector`를 통해 사용하는 것을 권장한다.
|
|
181
|
+
|
|
182
|
+
```typescript
|
|
183
|
+
export class OrmClientDbContextExecutor implements DbContextExecutor {
|
|
184
|
+
constructor(
|
|
185
|
+
private readonly _client: ServiceClient,
|
|
186
|
+
private readonly _opt: DbConnOptions & { configName: string },
|
|
187
|
+
);
|
|
188
|
+
async getInfo(): Promise<{ dialect: Dialect; database?: string; schema?: string }>;
|
|
189
|
+
async connect(): Promise<void>;
|
|
190
|
+
async beginTransaction(isolationLevel?: IsolationLevel): Promise<void>;
|
|
191
|
+
async commitTransaction(): Promise<void>;
|
|
192
|
+
async rollbackTransaction(): Promise<void>;
|
|
193
|
+
async close(): Promise<void>;
|
|
194
|
+
async executeDefs<T = Record<string, unknown>>(
|
|
195
|
+
defs: QueryDef[],
|
|
196
|
+
options?: (ResultMeta | undefined)[],
|
|
197
|
+
): Promise<T[][]>;
|
|
198
|
+
async executeParametrized(query: string, params?: unknown[]): Promise<unknown[][]>;
|
|
199
|
+
async bulkInsert(
|
|
200
|
+
tableName: string,
|
|
201
|
+
columnDefs: Record<string, ColumnMeta>,
|
|
202
|
+
records: Record<string, unknown>[],
|
|
203
|
+
): Promise<void>;
|
|
204
|
+
}
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
| Method | Description |
|
|
208
|
+
|--------|-------------|
|
|
209
|
+
| `getInfo()` | 서버에서 DB dialect, database, schema 조회 |
|
|
210
|
+
| `connect()` | 서버에서 DB 연결 생성. `_connId` 할당 |
|
|
211
|
+
| `beginTransaction(isolationLevel?)` | 트랜잭션 시작 |
|
|
212
|
+
| `commitTransaction()` | 트랜잭션 커밋 |
|
|
213
|
+
| `rollbackTransaction()` | 트랜잭션 롤백 |
|
|
214
|
+
| `close()` | DB 연결 종료 및 `_connId` 해제 |
|
|
215
|
+
| `executeDefs(defs, options?)` | QueryDef 배열을 서버에서 실행 |
|
|
216
|
+
| `executeParametrized(query, params?)` | 파라미터화된 쿼리를 서버에서 실행 |
|
|
217
|
+
| `bulkInsert(tableName, columnDefs, records)` | 대량 INSERT를 서버에서 실행 |
|
package/docs/main.md
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
# Main
|
|
2
|
+
|
|
3
|
+
## `ServiceClient`
|
|
4
|
+
|
|
5
|
+
WebSocket 기반 서비스 클라이언트의 최상위 파사드 클래스. `SocketProvider`, `ClientProtocolWrapper`, `ServiceTransport`, `EventClient`, `FileClient`를 내부적으로 조합한다.
|
|
6
|
+
|
|
7
|
+
```typescript
|
|
8
|
+
export class ServiceClient extends EventEmitter<ServiceClientEvents> {
|
|
9
|
+
constructor(
|
|
10
|
+
public readonly name: string,
|
|
11
|
+
public readonly options: ServiceConnectionOptions,
|
|
12
|
+
);
|
|
13
|
+
get connected(): boolean;
|
|
14
|
+
get hostUrl(): string;
|
|
15
|
+
getService<TService>(serviceName: string): ServiceProxy<TService>;
|
|
16
|
+
getEvent<TEventDef extends ServiceEventDef>(eventName: string): ClientEventProxy<TEventDef>;
|
|
17
|
+
async connect(): Promise<void>;
|
|
18
|
+
async close(): Promise<void>;
|
|
19
|
+
async send(
|
|
20
|
+
serviceName: string,
|
|
21
|
+
methodName: string,
|
|
22
|
+
params: unknown[],
|
|
23
|
+
progress?: ServiceProgress,
|
|
24
|
+
): Promise<unknown>;
|
|
25
|
+
async auth(token: string): Promise<void>;
|
|
26
|
+
async addListener<TEventDef extends ServiceEventDef>(
|
|
27
|
+
eventName: string,
|
|
28
|
+
info: TEventDef["$info"],
|
|
29
|
+
cb: (data: TEventDef["$data"]) => PromiseLike<void>,
|
|
30
|
+
): Promise<string>;
|
|
31
|
+
async removeListener(key: string): Promise<void>;
|
|
32
|
+
async emitEvent<TEventDef extends ServiceEventDef>(
|
|
33
|
+
eventName: string,
|
|
34
|
+
infoSelector: (item: TEventDef["$info"]) => boolean,
|
|
35
|
+
data: TEventDef["$data"],
|
|
36
|
+
): Promise<void>;
|
|
37
|
+
async uploadFile(
|
|
38
|
+
files: File[] | FileCollection | { name: string; data: BlobInput }[],
|
|
39
|
+
): Promise<ServiceUploadResult[]>;
|
|
40
|
+
async downloadFileBuffer(relPath: string): Promise<Bytes>;
|
|
41
|
+
}
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
`ServiceClient`가 발생시키는 이벤트 (`EventEmitter<ServiceClientEvents>`):
|
|
45
|
+
|
|
46
|
+
| Event | Data Type | Description |
|
|
47
|
+
|-------|-----------|-------------|
|
|
48
|
+
| `request-progress` | `ServiceProgressState` | 요청 전송 progress |
|
|
49
|
+
| `response-progress` | `ServiceProgressState` | 응답 수신 progress |
|
|
50
|
+
| `server-progress` | `ServiceProgressState` | 서버 내부 처리 progress |
|
|
51
|
+
| `state` | `"connected" \| "closed" \| "reconnecting"` | 연결 상태 변경 |
|
|
52
|
+
|
|
53
|
+
생성자 파라미터:
|
|
54
|
+
|
|
55
|
+
| Parameter | Type | Description |
|
|
56
|
+
|-----------|------|-------------|
|
|
57
|
+
| `name` | `string` | 클라이언트 식별자 (WebSocket URL 파라미터 및 HTTP 헤더로 전달됨) |
|
|
58
|
+
| `options` | `ServiceConnectionOptions` | 연결 옵션 (host, port, ssl, maxReconnectCount) |
|
|
59
|
+
|
|
60
|
+
주요 메서드:
|
|
61
|
+
|
|
62
|
+
| Method | Description |
|
|
63
|
+
|--------|-------------|
|
|
64
|
+
| `connect()` | WebSocket 연결 시작 |
|
|
65
|
+
| `close()` | WebSocket 연결 종료 및 protocol dispose |
|
|
66
|
+
| `auth(token)` | 서버에 인증 토큰 전송. 재연결 시 자동 재인증됨 |
|
|
67
|
+
| `getService<TService>(serviceName)` | 타입 안전한 서비스 프록시 반환 |
|
|
68
|
+
| `getEvent<TEventDef>(eventName)` | 타입 안전한 이벤트 프록시 반환. `ClientEventProxy<TEventDef>`를 반환하며 이벤트 이름과 타입이 캡처됨 |
|
|
69
|
+
| `send(serviceName, methodName, params, progress?)` | 서비스 메서드 원격 호출 |
|
|
70
|
+
| `addListener(eventName, info, cb)` | 서버 이벤트 구독. 제네릭 `TEventDef`로 타입 안전성 보장. 연결 상태여야 함 |
|
|
71
|
+
| `removeListener(key)` | 서버 이벤트 구독 해제 |
|
|
72
|
+
| `emitEvent(eventName, infoSelector, data)` | 서버 이벤트 발행. 제네릭 `TEventDef`로 타입 안전성 보장 |
|
|
73
|
+
| `uploadFile(files)` | 파일 업로드. `auth()` 호출 후 사용해야 함 |
|
|
74
|
+
| `downloadFileBuffer(relPath)` | 파일 다운로드 (`Uint8Array` 반환) |
|
|
75
|
+
|
|
76
|
+
접근자:
|
|
77
|
+
|
|
78
|
+
| Property | Type | Description |
|
|
79
|
+
|----------|------|-------------|
|
|
80
|
+
| `connected` | `boolean` | 현재 WebSocket 연결 상태 |
|
|
81
|
+
| `hostUrl` | `string` | HTTP 기본 URL (`http(s)://host:port`) |
|
|
82
|
+
|
|
83
|
+
## `ServiceProxy`
|
|
84
|
+
|
|
85
|
+
`TService`의 모든 메서드 반환 타입을 `Promise`로 래핑하는 유틸리티 타입. `ServiceClient.getService<TService>()`의 반환 타입으로 사용된다.
|
|
86
|
+
|
|
87
|
+
```typescript
|
|
88
|
+
export type ServiceProxy<TService> = {
|
|
89
|
+
[K in keyof TService]: TService[K] extends (...args: infer P) => infer R
|
|
90
|
+
? (...args: P) => Promise<Awaited<R>>
|
|
91
|
+
: never;
|
|
92
|
+
};
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
함수가 아닌 속성(`never`)은 타입에서 제외된다.
|
|
96
|
+
|
|
97
|
+
## `createServiceClient`
|
|
98
|
+
|
|
99
|
+
`ServiceClient` 팩토리 함수. `new ServiceClient(name, options)`와 동일하다.
|
|
100
|
+
|
|
101
|
+
```typescript
|
|
102
|
+
export function createServiceClient(name: string, options: ServiceConnectionOptions): ServiceClient;
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
| Parameter | Type | Description |
|
|
106
|
+
|-----------|------|-------------|
|
|
107
|
+
| `name` | `string` | 클라이언트 식별자 |
|
|
108
|
+
| `options` | `ServiceConnectionOptions` | 연결 옵션 |
|
|
109
|
+
|
|
110
|
+
사용 예:
|
|
111
|
+
|
|
112
|
+
```typescript
|
|
113
|
+
import { ServiceClient } from "@simplysm/service-client";
|
|
114
|
+
|
|
115
|
+
const client = new ServiceClient("my-app", {
|
|
116
|
+
host: "localhost",
|
|
117
|
+
port: 3000,
|
|
118
|
+
ssl: false,
|
|
119
|
+
maxReconnectCount: 10,
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
await client.connect();
|
|
123
|
+
await client.auth("my-auth-token");
|
|
124
|
+
|
|
125
|
+
// 타입 안전한 서비스 호출
|
|
126
|
+
const userSvc = client.getService<UserService>("User");
|
|
127
|
+
const users = await userSvc.getList();
|
|
128
|
+
|
|
129
|
+
// 이벤트 프록시 방식 (권장 — getService()와 동일한 패턴)
|
|
130
|
+
const chatEvt = client.getEvent<typeof ChatEvent>("Chat");
|
|
131
|
+
const key = await chatEvt.addListener({ roomId: "room-1" }, async (data) => {
|
|
132
|
+
// data.message는 string으로 타입 추론
|
|
133
|
+
});
|
|
134
|
+
await chatEvt.removeListener(key);
|
|
135
|
+
|
|
136
|
+
// 직접 호출 방식 (하위 호환)
|
|
137
|
+
const key2 = await client.addListener<typeof ChatEvent>("Chat", { roomId: "room-1" }, async (data) => {
|
|
138
|
+
// data.message
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
// 파일 업로드
|
|
142
|
+
const results = await client.uploadFile([{ name: "file.txt", data: "hello" }]);
|
|
143
|
+
|
|
144
|
+
// 파일 다운로드
|
|
145
|
+
const bytes = await client.downloadFileBuffer("/files/report.pdf");
|
|
146
|
+
|
|
147
|
+
await client.close();
|
|
148
|
+
```
|
package/docs/protocol.md
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
# Protocol
|
|
2
|
+
|
|
3
|
+
## `ClientProtocolWrapper`
|
|
4
|
+
|
|
5
|
+
메시지 인코딩/디코딩 인터페이스. 데이터 크기가 30KB 이상이면 Web Worker로 처리를 오프로드한다.
|
|
6
|
+
|
|
7
|
+
```typescript
|
|
8
|
+
export interface ClientProtocolWrapper {
|
|
9
|
+
encode(uuid: string, message: ServiceMessage): Promise<{ chunks: Bytes[]; totalSize: number }>;
|
|
10
|
+
decode(bytes: Bytes): Promise<ServiceMessageDecodeResult<ServiceMessage>>;
|
|
11
|
+
dispose(): void;
|
|
12
|
+
}
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
| Member | Type | Description |
|
|
16
|
+
|--------|------|-------------|
|
|
17
|
+
| `encode(uuid, message)` | `Promise<{ chunks: Bytes[]; totalSize: number }>` | 메시지를 바이너리 청크로 인코딩. 큰 데이터는 Worker로 오프로드 |
|
|
18
|
+
| `decode(bytes)` | `Promise<ServiceMessageDecodeResult<ServiceMessage>>` | 바이너리를 메시지로 디코딩. 큰 데이터는 Worker로 오프로드 (zero-copy 전송) |
|
|
19
|
+
| `dispose()` | `void` | 내부 `ServiceProtocol`과 Worker resolver 맵 정리 |
|
|
20
|
+
|
|
21
|
+
## `createClientProtocolWrapper`
|
|
22
|
+
|
|
23
|
+
`ClientProtocolWrapper` 팩토리 함수.
|
|
24
|
+
|
|
25
|
+
```typescript
|
|
26
|
+
export function createClientProtocolWrapper(protocol: ServiceProtocol): ClientProtocolWrapper;
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
| Parameter | Type | Description |
|
|
30
|
+
|-----------|------|-------------|
|
|
31
|
+
| `protocol` | `ServiceProtocol` | `@simplysm/service-common`의 `createServiceProtocol()`로 생성한 프로토콜 인스턴스 |
|
|
32
|
+
|
|
33
|
+
내부 동작:
|
|
34
|
+
- 임계값: 30KB (`30 * 1024` bytes)
|
|
35
|
+
- Worker가 지원되지 않는 환경(Node.js)에서는 메인 스레드에서 처리
|
|
36
|
+
- Worker는 싱글턴 패턴으로 공유됨 (`createClientProtocolWrapper` 여러 번 호출해도 Worker는 하나)
|
|
37
|
+
- Worker 작업은 60초 타임아웃 후 자동 reject (메모리 누수 방지)
|
|
38
|
+
- `decode` 시 Worker로 `ArrayBuffer` 소유권 이전 (zero-copy), 결과에서 `DateTime` 등 클래스 인스턴스 복원
|
|
39
|
+
|
|
40
|
+
**CRITICAL — Worker 생성 패턴 제약:**
|
|
41
|
+
Worker 생성 시 반드시 `new Worker(new URL("...", import.meta.url))` 직접 패턴을 사용해야 한다. sd-cli의 esbuild Worker 번들링 플러그인(`sd-worker-bundle`)이 AST에서 `new Worker(new URL(..., import.meta.url))` 패턴만 인식하여 Worker 파일을 별도 번들로 분리한다. 래퍼 함수(예: `createBrowserWorker(new URL(...))`)로 감싸면 `CallExpression`이 되어 플러그인이 인식하지 못하고, Worker 파일이 번들에 포함되지 않아 브라우저에서 404 에러가 발생한다.
|
|
42
|
+
|
|
43
|
+
사용 예:
|
|
44
|
+
|
|
45
|
+
```typescript
|
|
46
|
+
import { createClientProtocolWrapper } from "@simplysm/service-client";
|
|
47
|
+
import { createServiceProtocol } from "@simplysm/service-common";
|
|
48
|
+
|
|
49
|
+
const protocol = createServiceProtocol();
|
|
50
|
+
const wrapper = createClientProtocolWrapper(protocol);
|
|
51
|
+
|
|
52
|
+
const { chunks, totalSize } = await wrapper.encode("uuid-1", { name: "User.getList", body: [] });
|
|
53
|
+
|
|
54
|
+
// 사용 완료 후 정리
|
|
55
|
+
wrapper.dispose();
|
|
56
|
+
```
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
# Transport
|
|
2
|
+
|
|
3
|
+
## `SocketProviderEvents`
|
|
4
|
+
|
|
5
|
+
`SocketProvider`에서 발생하는 이벤트 타입 맵.
|
|
6
|
+
|
|
7
|
+
```typescript
|
|
8
|
+
export interface SocketProviderEvents {
|
|
9
|
+
message: Bytes;
|
|
10
|
+
state: "connected" | "closed" | "reconnecting";
|
|
11
|
+
}
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
| Event | Type | Description |
|
|
15
|
+
|-------|------|-------------|
|
|
16
|
+
| `message` | `Bytes` | 서버로부터 바이너리 메시지 수신 |
|
|
17
|
+
| `state` | `"connected" \| "closed" \| "reconnecting"` | 연결 상태 변경 |
|
|
18
|
+
|
|
19
|
+
## `SocketProvider`
|
|
20
|
+
|
|
21
|
+
WebSocket 연결, 재연결, 하트비트를 관리하는 인터페이스. 팩토리 함수 `createSocketProvider`로 생성한다.
|
|
22
|
+
|
|
23
|
+
```typescript
|
|
24
|
+
export interface SocketProvider {
|
|
25
|
+
readonly clientName: string;
|
|
26
|
+
readonly connected: boolean;
|
|
27
|
+
on<K extends keyof SocketProviderEvents & string>(
|
|
28
|
+
type: K,
|
|
29
|
+
listener: (data: SocketProviderEvents[K]) => void,
|
|
30
|
+
): void;
|
|
31
|
+
off<K extends keyof SocketProviderEvents & string>(
|
|
32
|
+
type: K,
|
|
33
|
+
listener: (data: SocketProviderEvents[K]) => void,
|
|
34
|
+
): void;
|
|
35
|
+
connect(): Promise<void>;
|
|
36
|
+
close(): Promise<void>;
|
|
37
|
+
send(data: Bytes): Promise<void>;
|
|
38
|
+
}
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
| Member | Type | Description |
|
|
42
|
+
|--------|------|-------------|
|
|
43
|
+
| `clientName` | `string` | 클라이언트 식별자 (읽기 전용) |
|
|
44
|
+
| `connected` | `boolean` | 현재 연결 상태 (읽기 전용) |
|
|
45
|
+
| `on(type, listener)` | `void` | 이벤트 리스너 등록 |
|
|
46
|
+
| `off(type, listener)` | `void` | 이벤트 리스너 제거 |
|
|
47
|
+
| `connect()` | `Promise<void>` | WebSocket 연결 시작 |
|
|
48
|
+
| `close()` | `Promise<void>` | WebSocket 연결 종료 |
|
|
49
|
+
| `send(data)` | `Promise<void>` | 바이너리 데이터 전송. 연결 복구 대기 후 전송 |
|
|
50
|
+
|
|
51
|
+
## `createSocketProvider`
|
|
52
|
+
|
|
53
|
+
`SocketProvider` 팩토리 함수.
|
|
54
|
+
|
|
55
|
+
```typescript
|
|
56
|
+
export function createSocketProvider(
|
|
57
|
+
url: string,
|
|
58
|
+
clientName: string,
|
|
59
|
+
maxReconnectCount: number,
|
|
60
|
+
): SocketProvider;
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
| Parameter | Type | Description |
|
|
64
|
+
|-----------|------|-------------|
|
|
65
|
+
| `url` | `string` | WebSocket 서버 URL (`ws://` 또는 `wss://`) |
|
|
66
|
+
| `clientName` | `string` | 클라이언트 식별자 (URL 파라미터로 전달됨) |
|
|
67
|
+
| `maxReconnectCount` | `number` | 최대 재연결 횟수. `0`이면 재연결 안 함 |
|
|
68
|
+
|
|
69
|
+
내부 동작:
|
|
70
|
+
- 하트비트: 5초마다 ping 전송, 30초 응답 없으면 재연결 시도
|
|
71
|
+
- 재연결: 연결 끊김 시 3초 간격으로 `maxReconnectCount`회 재시도
|
|
72
|
+
- Node.js 환경에서 `globalThis.WebSocket`이 없으면 `ws` 패키지로 폴리필
|
|
73
|
+
|
|
74
|
+
## `ServiceTransportEvents`
|
|
75
|
+
|
|
76
|
+
`ServiceTransport`에서 발생하는 이벤트 타입 맵.
|
|
77
|
+
|
|
78
|
+
```typescript
|
|
79
|
+
export interface ServiceTransportEvents {
|
|
80
|
+
event: { keys: string[]; data: unknown };
|
|
81
|
+
}
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
| Event | Type | Description |
|
|
85
|
+
|-------|------|-------------|
|
|
86
|
+
| `event` | `{ keys: string[]; data: unknown }` | 서버에서 발행된 이벤트 수신 |
|
|
87
|
+
|
|
88
|
+
## `ServiceTransport`
|
|
89
|
+
|
|
90
|
+
요청-응답 매핑, progress 중계, 서버 이벤트 디스패치를 담당하는 인터페이스.
|
|
91
|
+
|
|
92
|
+
```typescript
|
|
93
|
+
export interface ServiceTransport {
|
|
94
|
+
on<K extends keyof ServiceTransportEvents & string>(
|
|
95
|
+
type: K,
|
|
96
|
+
listener: (data: ServiceTransportEvents[K]) => void,
|
|
97
|
+
): void;
|
|
98
|
+
off<K extends keyof ServiceTransportEvents & string>(
|
|
99
|
+
type: K,
|
|
100
|
+
listener: (data: ServiceTransportEvents[K]) => void,
|
|
101
|
+
): void;
|
|
102
|
+
send(message: ServiceClientMessage, progress?: ServiceProgress): Promise<unknown>;
|
|
103
|
+
}
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
| Member | Type | Description |
|
|
107
|
+
|--------|------|-------------|
|
|
108
|
+
| `on(type, listener)` | `void` | 이벤트 리스너 등록 |
|
|
109
|
+
| `off(type, listener)` | `void` | 이벤트 리스너 제거 |
|
|
110
|
+
| `send(message, progress?)` | `Promise<unknown>` | 서버에 메시지 전송하고 응답 대기 |
|
|
111
|
+
|
|
112
|
+
## `createServiceTransport`
|
|
113
|
+
|
|
114
|
+
`ServiceTransport` 팩토리 함수.
|
|
115
|
+
|
|
116
|
+
```typescript
|
|
117
|
+
export function createServiceTransport(
|
|
118
|
+
socket: SocketProvider,
|
|
119
|
+
protocol: ClientProtocolWrapper,
|
|
120
|
+
): ServiceTransport;
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
| Parameter | Type | Description |
|
|
124
|
+
|-----------|------|-------------|
|
|
125
|
+
| `socket` | `SocketProvider` | WebSocket 소켓 제공자 |
|
|
126
|
+
| `protocol` | `ClientProtocolWrapper` | 인코딩/디코딩 래퍼 |
|
|
127
|
+
|
|
128
|
+
내부 동작:
|
|
129
|
+
- `uuid` 기반 요청-응답 `Map`으로 비동기 응답을 매핑
|
|
130
|
+
- 소켓 `closed`/`reconnecting` 상태 시 대기 중인 모든 요청을 reject
|
|
131
|
+
- 분할 메시지의 progress 상태를 추적하여 완료 시 100% 이벤트 전송
|
package/docs/types.md
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
# Types
|
|
2
|
+
|
|
3
|
+
## `BlobInput`
|
|
4
|
+
|
|
5
|
+
Blob constructor가 허용하는 데이터 타입. DOM `BlobPart`를 대체하여 Node.js / 브라우저 양쪽에서 typecheck가 통과하도록 한다.
|
|
6
|
+
|
|
7
|
+
```typescript
|
|
8
|
+
export type BlobInput = Blob | Uint8Array<ArrayBuffer> | ArrayBuffer | string;
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## `FileCollection`
|
|
12
|
+
|
|
13
|
+
File 컬렉션 인터페이스. DOM `FileList`를 대체하며 브라우저 `FileList`와 구조적으로 호환된다.
|
|
14
|
+
|
|
15
|
+
```typescript
|
|
16
|
+
export interface FileCollection {
|
|
17
|
+
readonly length: number;
|
|
18
|
+
item(index: number): File | null;
|
|
19
|
+
[index: number]: File;
|
|
20
|
+
[Symbol.iterator](): IterableIterator<File>;
|
|
21
|
+
}
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
| Field | Type | Description |
|
|
25
|
+
|-------|------|-------------|
|
|
26
|
+
| `length` | `number` | 파일 개수 |
|
|
27
|
+
| `item(index)` | `File \| null` | 인덱스로 File 반환 |
|
|
28
|
+
| `[index]` | `File` | 인덱스 접근자 |
|
|
29
|
+
| `[Symbol.iterator]()` | `IterableIterator<File>` | for-of 이터레이션 지원 |
|
|
30
|
+
|
|
31
|
+
## `isWorkerSupported`
|
|
32
|
+
|
|
33
|
+
Web Worker API 지원 여부를 확인한다. `globalThis.Worker` 존재 여부로 판별한다.
|
|
34
|
+
|
|
35
|
+
```typescript
|
|
36
|
+
export function isWorkerSupported(): boolean;
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## `ServiceConnectionOptions`
|
|
40
|
+
|
|
41
|
+
서비스 서버에 연결할 때 사용하는 옵션 인터페이스.
|
|
42
|
+
|
|
43
|
+
```typescript
|
|
44
|
+
export interface ServiceConnectionOptions {
|
|
45
|
+
port: number;
|
|
46
|
+
host: string;
|
|
47
|
+
ssl?: boolean;
|
|
48
|
+
maxReconnectCount?: number;
|
|
49
|
+
}
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
| Field | Type | Description |
|
|
53
|
+
|-------|------|-------------|
|
|
54
|
+
| `port` | `number` | 서버 포트 번호 |
|
|
55
|
+
| `host` | `string` | 서버 호스트 주소 |
|
|
56
|
+
| `ssl` | `boolean?` | HTTPS/WSS 사용 여부 |
|
|
57
|
+
| `maxReconnectCount` | `number?` | 최대 재연결 횟수. `0`이면 재연결 비활성화. 기본값 `10` |
|
|
58
|
+
|
|
59
|
+
## `ServiceProgress`
|
|
60
|
+
|
|
61
|
+
요청/응답/서버 단계별 progress 콜백을 담는 컨테이너 인터페이스.
|
|
62
|
+
|
|
63
|
+
```typescript
|
|
64
|
+
export interface ServiceProgress {
|
|
65
|
+
request?: (s: ServiceProgressState) => void;
|
|
66
|
+
response?: (s: ServiceProgressState) => void;
|
|
67
|
+
server?: (s: ServiceProgressState) => void;
|
|
68
|
+
}
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
| Field | Type | Description |
|
|
72
|
+
|-------|------|-------------|
|
|
73
|
+
| `request` | `((s: ServiceProgressState) => void)?` | 클라이언트 → 서버 전송 progress |
|
|
74
|
+
| `response` | `((s: ServiceProgressState) => void)?` | 서버 → 클라이언트 수신 progress |
|
|
75
|
+
| `server` | `((s: ServiceProgressState) => void)?` | 서버 내부 처리 progress |
|
|
76
|
+
|
|
77
|
+
## `ServiceProgressState`
|
|
78
|
+
|
|
79
|
+
progress 콜백에 전달되는 상태 객체.
|
|
80
|
+
|
|
81
|
+
```typescript
|
|
82
|
+
export interface ServiceProgressState {
|
|
83
|
+
uuid: string;
|
|
84
|
+
totalSize: number;
|
|
85
|
+
completedSize: number;
|
|
86
|
+
}
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
| Field | Type | Description |
|
|
90
|
+
|-------|------|-------------|
|
|
91
|
+
| `uuid` | `string` | 요청 식별자 |
|
|
92
|
+
| `totalSize` | `number` | 전체 크기 (bytes) |
|
|
93
|
+
| `completedSize` | `number` | 완료된 크기 (bytes) |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@simplysm/service-client",
|
|
3
|
-
"version": "14.0.
|
|
3
|
+
"version": "14.0.49",
|
|
4
4
|
"description": "심플리즘 패키지 - 서비스 (client)",
|
|
5
5
|
"author": "심플리즘",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -14,14 +14,15 @@
|
|
|
14
14
|
"types": "./dist/index.d.ts",
|
|
15
15
|
"files": [
|
|
16
16
|
"dist",
|
|
17
|
-
"src"
|
|
17
|
+
"src",
|
|
18
|
+
"docs"
|
|
18
19
|
],
|
|
19
20
|
"sideEffects": false,
|
|
20
21
|
"dependencies": {
|
|
21
22
|
"consola": "^3.4.2",
|
|
22
|
-
"@simplysm/core-common": "14.0.
|
|
23
|
-
"@simplysm/
|
|
24
|
-
"@simplysm/
|
|
23
|
+
"@simplysm/core-common": "14.0.49",
|
|
24
|
+
"@simplysm/service-common": "14.0.49",
|
|
25
|
+
"@simplysm/orm-common": "14.0.49"
|
|
25
26
|
},
|
|
26
27
|
"devDependencies": {
|
|
27
28
|
"@types/ws": "^8.18.1",
|