Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
요청 상태를 기반으로 API 요청에 활용되는 커넥터입니다. 접근 제어 및 stateless 커넥터를 연계 할 수 있습니다.
커넥터
어댑터에 위임
연결 가능한 커넥터
개요
call
O
params
, map
분산 서비스 액션을 호출합니다.
publish
O
params
중앙 메시징 서비스에 이벤트를 발행합니다.
subscribe
O
map
중앙 메시징 서비스에서 이벤트를 구독합니다.
GraphQL의 Subscription
타입이나 WebSocket 프로토콜 등을 사용하지 않거나, 분산 시스템에 중앙 메시징 서비스를 제공 할 수 없는 경우엔 publish
, subscribe
커넥터를 구현하지 않아도 무관합니다.
요청 상태가 없는 커넥터입니다.
커넥터
어댑터에 위임
개요
map
X
Inline JavaScript Function String을 VM에서 해석하여 주어진 객체나 응답 객체를 변환합니다.
params
X
요청 페이로드에서 위의 타 커넥터들로 전달 할 객체를 생성합니다.
discover
O
분산 서비스의 업데이트나 종료를 감지하고, 노드, 서비스 API Schema, 액션 및 이벤트 구독, 발행 정보를 수집합니다.
health
O
분산 서비스 및 액션, 중앙 메시징 서비스의 상태 확인을 제공합니다.
reporter
O
출처 노드로 디버그 메세지를 전달합니다.
logger
O
Gateway의 로깅 인스턴스를 제공합니다.
서비스 API 스키마는 서비스 브로커에 의존해 Gateway로 수집되고 처리됩니다. Moleculer 어댑터로 작성된 서비스 브로커의 경우 기본적으로 ServiceSchema
의 metadata.api
필드에서 서비스 API 스키마가 수집되기를 기대합니다.
서비스 API 스키마의 병합은 서비스 노드의 연결, 종료, 스키마 변경시 발생합니다. 서비스 API 스키마는 자신의 스키마를 병합 할 브랜치를 스키마에 명시합니다. Gateway에는 기본적으로 master
브랜치가 생성되어있으며, master
브랜치는 제거 될 수 없습니다.
protocol: {
이하 protocol 항목에 외부에 제공하려는 API를 작성하고 call
, publish
, subscribe
, map
커넥터에 맵핑합니다. 각 커넥터에 대한 추가적인 내용은 아래 Connectors for API Handler 섹션에서 다룹니다.
GraphQL API 맵핑에는 call
, publish
, subscribe
, map
커넥터를 이용 할 수 있습니다.
TypeDefs
GraphQL: {
typeDefs: `
"""Soccer Player"""
type Player implements Node {
id: ID!
email: String!
name: String!
photoURL: String
position: String
"""A team player belongs to"""
team: Team
}
extend type Query {
"""Current Player"""
viewer: Player
player(id: ID!): Player
}
extend type Subscription {
playerMessage: String!
playerUpdated: Player
}
`,
GraphQL 프로토콜에서 typeDefs
속성에 서비스에 필요한 정의(scalar
를 제외한 타입, 인터페이스, 열거형 등 모든 형태)을 추가하거나 기존 타입(API Gateway에서 제공하는 기본 타입과 분산 서비스에서 제공한 타입들)을 확장 할 수 있습니다.
Resolvers
resolvers: {
이하 리졸버에 각 타입들의 필드를 call
, publish
, subscribe
, map
커넥터에 맵핑합니다.
Player: {
리졸버가 할당되지 않은 필드들은 source 객체에서 동일한 이름의 속성으로부터 주입됩니다.
Call
team: {
call: {
action: "team.get",
params: {
id: "@source.teamId",
},
},
},
GraphQL API의 Query
및 Mutation
타입의 필드들에는 publish
및 call
또는 map
커넥터를 이용 할 수 있습니다. params
맵핑에는 @source
, @args
, @context
, @info
를 이용 할 수 있습니다.
Map
position: `({ source, args, context, info }) => source.position.toUpperCase()`,
`
GraphQL 프로토콜에서 map
커넥터 (Inline JavaScript Function String)는 간략하게 field: { map: <FN_STRING> }
대신에 field: <FN_STRING>
방식으로 작성 할 수 있습니다.
// be noted that special field __isTypeOf got only three arguments
__isTypeOf: `({ source, context, info }) => return source.someSpecialFieldForThisType != null`,
// be noted that special field __resolveType got only three arguments
__resolveType: `
({ source, context, info }) => {
if (source.someSpecialFieldForThisType != null) {
return "TypeA";
} else {
return "TypeB";
}
}
`,
},
위처럼 Union, Interface 구현 타입을 해석하기 위한 특수 필드에도 Inline JavaScript Function String를 사용합니다.
Batched Call (DataLoader)
Query: {
viewer: {
call: {
action: "player.get",
params: {
id: "@context.user.player.id[]",
},
},
},
player: {
call: {
action: "player.get",
params: {
id: "@args.id[]",
},
},
},
},
위처럼 인증 정보를 포함한 @context
나 GraphQL 필드 인자인 @args
를 활용해 동일한 액션을 서로 다른 방식으로 맵핑 할 수 있습니다.
또한 call
메소드는 GraphQL 요청에서 발생하기 쉬운 N+1 쿼리를 방지하기 위해 요청을 배치로 처리 할 수 있도록 설계되었습니다. (ref. Dataloader)
한 컨텍스트에서 여러번 호출되는 액션에 배칭을 지원하면 응답 속도를 획기적으로 높힐 수 있습니다. 배칭을 활성화하기 위해서는 call
커넥터의 batchedParams
필드에 배치 처리가 가능한 필드의 이름을 작성하고, 연결된 서비스 액션이 배열로 들어오는 인자 묶음을 처리 할 수 있도록 합니다.
query {
viewer {
id
email
}
one: player(id: 1) {
id
email
}
two: player(id: 2) {
id
email
}
three: player(id: 3) {
id
email
}
}
위와 같은 GraphQL 요청은 player.get
액션을 { id: [context.user.player.id, 1, 2, 3], ...(other common params) }
페이로드와 함께 한번만 호출하게 됩니다. 연결된 액션이 [{ ... }, { ... }, { ... }, { ... }]
묶음으로 응답을 주면 각 필드에 해당하는 응답이 할당됩니다.
만약 id: 3
인 플레이어가 없는 경우 배치 요청을 처리하는 과정에서 에러를 발생시켜 제어 흐름을 멈추는 대신에, 에러를 발생키지않고 배치 응답에 포함시키고 나머지 제어 흐름을 마무리합니다. [{ ... }, { ... }, { ... }, { message: "...", isBatchError: true, ... }]
처럼 isBatchError: true
속성을 갖는 에러 객체를 응답에 포함합니다.
Subscribe
Subscription: {
playerMessage: {
subscribe: {
events: ["player.message"],
},
},
GraphQL API의 Subscription
타입의 필드에서는 subscribe
커넥터를 사용 할 수 있습니다. params
맵핑에는 마찬가지로 @source
, @args
, @context
, @info
를 이용 할 수 있습니다. @source
에 이벤트 객체가 맵핑됩니다.
@source
객체는 { event, payload }
로 구성됩니다. Broker에 따라 기타 속성이 추가 될 수 있습니다.
playerMessage: {
subscribe: {
events: ["player.message"],
map: `({ source, args, context, info }) => source.payload.message`,
},
},
},
},
},
subscribe
커넥터에서는 위처럼 수신된 이벤트 페이로드를 다시 map
커넥터로 변환 할 수 있습니다. subscribe
커넥터 안에서 map
커넥터가 사용되지 않는 경우 이벤트 객체 전체(source
)를 반환합니다.
API Gateway constructor options.
APIGatewayOptions type is a kind of container for all the subordinate components' options.
type APIGatewayOptions = {
brokers: RecursivePartial<ServiceBrokerOptions>[],
schema: RecursivePartial<SchemaRegistryOptions>,
server: RecursivePartial<APIServerOptions>,
logger: LoggerConstructorOptions,
} & RecursivePartial<APIGatewayOwnOptions>;
name
default
description
brokers
-
Service Broker constructor options. Can configure multiple brokers for a single gateway. Service Broker discovers remote services and works as a delegator for calling remote service procedures and also deals with central event messages.
schema
-
Schema Registry constructor options. Schema Registry handles the integration of remote service API schema and creates API handlers. Can disable or configure detailed options for each API Schema Plugins like GraphQL, REST and WebSocket, etc.
server
-
API Server constructor options. Can configure API Server update policy, server components (HTTP, WebSocket server) and network interface (HTTP, HTTPS) detailed options, middleware options and request context factory options.
logger
-
Global logger options. Currently logger is supported.
Options for the gateway itself rather inner components.
type APIGatewayOwnOptions = {
skipProcessEventRegistration: boolean;
};
name
default
description
skipProcessEventRegistration
false
Set true to not to set default handlers for process interrupt signals like SIGINT.
Service Broker options are consist of common properties and delegator specific properties. The common properties show below.
type ServiceBrokerOptions = {
registry: ServiceRegistryOptions;
batching: BatchingPoolOptions;
function: InlineFunctionOptions;
reporter: ReporterOptions;
log: {
event: boolean;
call: boolean;
},
} & ServiceBrokerDelegatorConstructorOptions;
name
default
description
registry
-
Options for the ServiceRegistry which collect remote services, available procedures and event types, etc.
batching
-
Options for batching feature which utilize for concurrent multiple procedure calls.
function
-
Options for inline function (JS function notation string) sandbox.
reporter
-
Options for remote service reporter instance which reports API integration status, error or logging in inline function sandbox, etc.
log.event
true
Enable logging event messages.
log.call
true
Enable logging remote procedure call.
type ServiceRegistryOptions = {
examples: {
processIntervalSeconds: number;
queueLimit: number;
limitPerActions: number;
limitPerEvents: number;
streamNotation: string;
omittedNotation: string;
omittedLimit: number;
redactedNotation: string;
redactedParamNameRegExps: RegExp[];
};
healthCheck: {
intervalSeconds: number;
};
};
name
default
description
examples
-
Options for the ServiceRegistry action (remote procedure), event example collecting feature.
examples.processIntervalSeconds
5
Consume example queue for every given intervals.
examples.queueLimit
50
Example queue size.
examples.limitPerActions
10
Maximum number of examples for a single action (remote procedure).
examples.limitPerEvents
10
Maximum number of examples for a single event.
examples.streamNotation
*STREAM*
Replace stream request and response of an example to given string.
examples.omittedNotation
*OMITTED*
Truncate example object's string property and append given suffix for...
examples.omittedLimit
100
The strings longer than given length.
examples.redactedNotation
*REDACTED*
React example object's string property to given string for...
examples.redactedParamNameRegExps
[
/password/i,
/secret/i,
/credential/i,
/key/i,
/token/i,
]
Matched strings with given regular expressions.
healthCheck
-
Options for the ServiceRegistry health check feature.
healthCheck.intervalSeconds
10
Health check for every given intervals.
type BatchingPoolOptions = {
batchingKey: (...args: any[]) => any;
entryKey: (batchingParams: any) => any;
failedEntryCheck: (entry: any) => boolean;
entriesLimit: number;
};
name
default
description
batchingKey
(hash function)
A keygen function for the key of same batching arguments. Create hash string with args object by default.
entryKey
(hash function)
A keygen function for the variable params of each batched entries.
failedEntryCheck
entry => entry && entry.batchingError
A function to determine whether each entries are failed or not in a batch response. By default, a remote procedure which supports batching should response { ..., batchingError: true }
object for failed entry.
entriesLimit
100
Maximum number of entries for a single batch.
type InlineFunctionOptions = {
util: {[key: string]: any};
};
name
default
description
util
{}
Any kind of object which can be accessed as global util
variable from inline functions.
type ReporterOptions = {
tableWidthZoomFactor: number;
};
name
default
description
tableWidthZoomFactor
1
A reporter sends a report which is consist of raw messages and a string that prints messages as a shape of a table. For that table, set a zoom factor of the width.
Specific options for the Service Broker Delegator. Can choose only one among supported delegators. Currently moleculer delegator is supported.
type ServiceBrokerDelegatorConstructorOptions = {
moleculer?: MoleculerServiceBrokerDelegatorOptions;
[otherDelegatorKey]?: any;
};
name
default
description
moleculer
-
Service Broker Delegator options.
moleculer delegator can be configured with moleculer broker own options and few extra options like below.
import * as Moleculer from "moleculer";
type MoleculerServiceBrokerDelegatorOptions = Moleculer.BrokerOptions & {
batchedCallTimeout: (itemCount: number) => number;
streamingCallTimeout: number;
streamingToStringEncoding: "ascii" | "utf8" | "utf-8" | "utf16le" | "ucs2" | "ucs-2" | "base64" | "latin1" | "binary" | "hex";
services: Moleculer.ServiceSchema[];
};
name
default
description
batchedCallTimeout
(return 5-60s based on item count)
A function to calculate the timeout options for a batched call.
streamingCallTimeout
3600000 (1 hour)
A timeout options for a streaming call (ms).
streamingToStringEncoding
base64
An encoding which is used to transform streaming data to buffer data. This is for the case that non-root property of payload is a readable stream. Because moleculer service broker can pipe only a single streaming data at once in a single params, a gateway needs to transform non-root streaming data to buffer data before proxy the action call. Try to check your moleculer service broker transporter options and this option for a malformed streaming data issue.
services
[]
Given Moleculer.ServiceSchema[]
would be registered on moleculer service broker started. This is for the testing convenience.
Service Registry options are consist of own options for the registry itself and Protocol, Policy, this two type of Plugin constructor options.
type SchemaRegistryOptions = {
maxVersions: number;
maxUnusedSeconds: number;
protocol: ProtocolPluginConstructorOptions,
policy: PolicyPluginConstructorOptions,
};
name
default
description
maxVersions
10
Maximum number of old versions for each branches.
maxUnusedSeconds
1800
Maximum unused duration until deleting non-master branches.
protocol
-
A ProtocolPlugin handles mapping Public API to calling internal services' procedure, publishing and subscribing event messages.
policy
-
A PolicyPlugin handles access controls (authorization) while calling internal services' procedure, publishing and subscribing event messages.
type ProtocolPluginConstructorOptions = {
GraphQL: RecursivePartial<GraphQLProtocolPluginOptions> | false;
REST: RecursivePartial<RESTProtocolPluginOptions> | false;
WebSocket: RecursivePartial<WebSocketProtocolPluginOptions> | false;
}
export type PolicyPluginConstructorOptions = {
scope: RecursivePartial<ScopePolicyPluginOptions> | false;
filter: RecursivePartial<FilterPolicyPluginOptions> | false;
};