-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy paththrift-client.js
268 lines (257 loc) · 8.63 KB
/
thrift-client.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
const Thrift = require('node-thrift-protocol');
const Storage = require('./lib/storage');
const ThriftSchema = require('./lib/thrift-schema');
const { EventEmitter } = require('events');
const Header = require('./lib/header');
const TApplicationException = require('./lib/tapplicationexception');
const METHODS = Symbol();
const STORAGE = Symbol();
class SocketClosedByBackEnd extends Error {
constructor() {
super('socket closed by backend');
this.name = 'SOCKET_CLOSED_BY_BACKEND';
this.status = 503;
}
}
class ThriftServerListener extends EventEmitter {
constructor({ server, port, schema }) {
super();
Object.defineProperty(this, METHODS, { value: [] });
if (server) {
server.on('connection', socket => {
let thrift = new Thrift(socket);
let client = new ThriftClient({ thrift, schema });
client.on('error', () => client.end());
this[METHODS].forEach(args => client.register(...args));
});
} else {
server = Thrift.createServer(thrift => {
let client = new ThriftClient({ thrift, schema });
client.on('error', () => client.end());
this[METHODS].forEach(args => client.register(...args));
});
if (port) server.listen(+port);
}
this.server = server;
}
register(...args) {
this[METHODS].push(args);
return this;
}
address() {
return this.server.address();
}
listen(...args) {
return this.server.listen(...args);
}
close() {
return this.server.close();
}
}
let tcReceive = (that, { id, type, name, fields }) => {
let api = that.schema.service[name];
switch (type) {
case 'CALL':
if (that.hasRegistered(name)) {
new Promise((resolve, reject) => {
try {
let params = that.schema.decodeStruct(api.args, { fields });
resolve(that.trigger(name, params));
} catch (error) {
reject(error);
}
}).then(result => {
result = that.schema.encodeValueWithType(result, api.type);
result.id = 0;
let fields = [ result ];
that.thrift.write({ id, type: 'REPLY', name, fields });
}).catch(error => {
let fields;
try {
fields = that.schema.encodeStruct(api.throws, error).fields;
if (!fields.length) throw error;
that.thrift.write({ id, type: 'REPLY', name, fields });
} catch (error) {
let fields = that.schema.encodeStruct(TApplicationException.SCHEMA, {
message: error.stack || error.message || error.name,
type: TApplicationException.TYPE_ENUM.INTERNAL_ERROR
}).fields;
that.thrift.write({ id, type: 'EXCEPTION', name, fields });
}
});
} else {
let fields = that.schema.encodeStruct(TApplicationException.SCHEMA, {
message: `method '${name}' is not found`,
type: TApplicationException.TYPE_ENUM.UNKNOWN_METHOD
}).fields;
that.thrift.write({ id, type: 'EXCEPTION', name, fields });
}
break;
case 'ONEWAY':
if (that.hasRegistered(name)) {
try {
let params = that.schema.decodeStruct(api.args, { fields });
that.trigger(name, params);
} catch (error) {
/* ignore oneway error */
}
}
break;
case 'EXCEPTION': {
let item = that[STORAGE].take(id);
if (!item) {
return;
}
clearTimeout(item.timer);
let params = that.schema.decodeStruct(TApplicationException.SCHEMA, { fields });
item.reject(new TApplicationException(params.type, params.message));
break;
}
case 'REPLY': {
let item = that[STORAGE].take(id);
if (!item) {
return;
}
clearTimeout(item.timer);
let resolve = item.resolve;
let reject = item.reject;
if (fields.length === 0) fields = [ { id: 0, type: 'VOID' } ];
let field = fields[0];
if (field.id) {
let errorType = api.throws.find(item => +item.id === +field.id);
if (errorType) {
let type = errorType.name;
let data = that.schema.decodeValueWithType(field, errorType.type);
reject({ name: 'THRIFT_EXCEPTION', type, data });
} else {
reject({ name: 'THRIFT_ERROR', field });
}
} else {
try {
resolve(that.schema.decodeValueWithType(field, api.type));
} catch (reason) {
reject(reason);
}
}
break;
}
default:
throw Error('No Implement');
}
};
const tcError = (that, reason) => {
if (that.state === 'CLOSED') return;
that[STORAGE].takeForEach(({ reject }) => reject(reason));
if (that.retryDefer > 0) setTimeout(() => that.reset(), that.retryDefer);
that.thrift.removeAllListeners();
that.thrift.on('error', () => { /* ignore */ });
that.emit('error', reason);
};
const tcConnect = (that) => {
if (that.state === 'CLOSED') return;
that.state = 'CONNECTED';
that.emit('connect');
};
const destroyThriftConnection = connection => {
connection.removeAllListeners();
connection.on('error', () => { /* ignore */ });
connection.end();
connection.socket.destroy();
};
class ThriftClientTimeoutError extends Error {
constructor(message) {
super(message || 'ThriftClient call time out');
this.status = 504;
this.name = 'THRIFT_CLIENT_TIMEOUT';
}
}
class ThriftClient extends EventEmitter {
static start(args) {
return new ThriftServerListener(args);
}
constructor(options) {
super();
this.state = 'INITIAL';
Object.defineProperty(this, METHODS, { value: {} });
Object.defineProperty(this, STORAGE, { value: new Storage() });
Object.assign(this, options, { thrift: null });
this.ignoreResponseCheck = !!options.ignoreResponseCheck;
if (!('retryDefer' in this)) this.retryDefer = 1000;
// Don't retry, if thrift object has specified.
if (options.thrift) this.retryDefer = 0;
this.reset(options.thrift);
}
set schema(data) {
let { ignoreResponseCheck } = this;
let schema = new ThriftSchema(data, { ignoreResponseCheck });
let desc = Object.getOwnPropertyDescriptor(ThriftClient.prototype, 'schema');
desc.get = () => schema;
Object.defineProperty(this, 'schema', desc);
}
reset(thrift) {
let host = this.host || '127.0.0.1';
let port = this.port || 3000;
if (!thrift) thrift = Thrift.connect({ host, port });
thrift.on('error', reason => tcError(this, reason));
thrift.on('timeout', reason => tcError(this, reason));
thrift.on('end', () => tcError(this, new SocketClosedByBackEnd()));
thrift.on('data', message => tcReceive(this, message));
thrift.on('connect', () => tcConnect(this));
if (this.thrift) destroyThriftConnection(this.thrift);
this.thrift = thrift;
}
call(name, params = {}, header, settings = {}) {
let api = this.schema.service[name];
return new Promise((resolve, reject) => {
if (!api) return reject(new Error(`API ${JSON.stringify(name)} not found`));
let fields = this.schema.encodeStruct(api.args, params).fields;
let timer;
const timeout = +settings.timeout;
// timeout is Number or NaN, but NaN !== NaN.
if (timeout === timeout) {
timer = setTimeout(() => {
this[STORAGE].take(id);
reject(new ThriftClientTimeoutError());
}, timeout);
}
let id = this[STORAGE].push({ resolve, reject, timer });
if (header) header = Header.encode(header);
try {
this.thrift.write({ id, name, type: 'CALL', fields, header });
} catch (e) {
this[STORAGE].take(id);
reject(e);
}
});
}
oneway(name, params = {}, header) {
let api = this.schema.service[name];
return new Promise((resolve, reject) => {
if (!api) return reject(new Error(`API ${JSON.stringify(name)} not found`));
let fields = this.schema.encodeStruct(api.args, params).fields;
let id = this[STORAGE].noop();
if (header) header = Header.encode(header);
this.thrift.write({ id, name, type: 'ONEWAY', fields, header });
resolve();
});
}
register(name, ...handlers) {
const chains = (ctx, index = 0) => {
if (index >= handlers.length) return null;
let handler = handlers[index];
if (typeof handler !== 'function') return chains(ctx, index + 1);
return handler.call(this, ctx, () => chains(ctx, index + 1));
};
this[METHODS][name] = chains;
return this;
}
end() {
this.state = 'CLOSED';
destroyThriftConnection(this.thrift);
}
hasRegistered(name) { return name in this[METHODS]; }
trigger(name, ctx) {
return Promise.resolve(ctx).then(this[METHODS][name]);
}
}
module.exports = ThriftClient;