chenyc
2025-12-09 65e034683b28d799e73c7d7e5e4769fab5b9bc9c
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
/**
 * http.js: Transport for outputting to a json-rpcserver.
 *
 * (C) 2010 Charlie Robbins
 * MIT LICENCE
 */
 
'use strict';
 
const http = require('http');
const https = require('https');
const { Stream } = require('readable-stream');
const TransportStream = require('winston-transport');
const { configure } = require('safe-stable-stringify');
 
/**
 * Transport for outputting to a json-rpc server.
 * @type {Stream}
 * @extends {TransportStream}
 */
module.exports = class Http extends TransportStream {
  /**
   * Constructor function for the Http transport object responsible for
   * persisting log messages and metadata to a terminal or TTY.
   * @param {!Object} [options={}] - Options for this instance.
   */
  // eslint-disable-next-line max-statements
  constructor(options = {}) {
    super(options);
 
    this.options = options;
    this.name = options.name || 'http';
    this.ssl = !!options.ssl;
    this.host = options.host || 'localhost';
    this.port = options.port;
    this.auth = options.auth;
    this.path = options.path || '';
    this.maximumDepth = options.maximumDepth;
    this.agent = options.agent;
    this.headers = options.headers || {};
    this.headers['content-type'] = 'application/json';
    this.batch = options.batch || false;
    this.batchInterval = options.batchInterval || 5000;
    this.batchCount = options.batchCount || 10;
    this.batchOptions = [];
    this.batchTimeoutID = -1;
    this.batchCallback = {};
 
    if (!this.port) {
      this.port = this.ssl ? 443 : 80;
    }
  }
 
  /**
   * Core logging method exposed to Winston.
   * @param {Object} info - TODO: add param description.
   * @param {function} callback - TODO: add param description.
   * @returns {undefined}
   */
  log(info, callback) {
    this._request(info, null, null, (err, res) => {
      if (res && res.statusCode !== 200) {
        err = new Error(`Invalid HTTP Status Code: ${res.statusCode}`);
      }
 
      if (err) {
        this.emit('warn', err);
      } else {
        this.emit('logged', info);
      }
    });
 
    // Remark: (jcrugzz) Fire and forget here so requests dont cause buffering
    // and block more requests from happening?
    if (callback) {
      setImmediate(callback);
    }
  }
 
  /**
   * Query the transport. Options object is optional.
   * @param {Object} options -  Loggly-like query options for this instance.
   * @param {function} callback - Continuation to respond to when complete.
   * @returns {undefined}
   */
  query(options, callback) {
    if (typeof options === 'function') {
      callback = options;
      options = {};
    }
 
    options = {
      method: 'query',
      params: this.normalizeQuery(options)
    };
 
    const auth = options.params.auth || null;
    delete options.params.auth;
 
    const path = options.params.path || null;
    delete options.params.path;
 
    this._request(options, auth, path, (err, res, body) => {
      if (res && res.statusCode !== 200) {
        err = new Error(`Invalid HTTP Status Code: ${res.statusCode}`);
      }
 
      if (err) {
        return callback(err);
      }
 
      if (typeof body === 'string') {
        try {
          body = JSON.parse(body);
        } catch (e) {
          return callback(e);
        }
      }
 
      callback(null, body);
    });
  }
 
  /**
   * Returns a log stream for this transport. Options object is optional.
   * @param {Object} options - Stream options for this instance.
   * @returns {Stream} - TODO: add return description
   */
  stream(options = {}) {
    const stream = new Stream();
    options = {
      method: 'stream',
      params: options
    };
 
    const path = options.params.path || null;
    delete options.params.path;
 
    const auth = options.params.auth || null;
    delete options.params.auth;
 
    let buff = '';
    const req = this._request(options, auth, path);
 
    stream.destroy = () => req.destroy();
    req.on('data', data => {
      data = (buff + data).split(/\n+/);
      const l = data.length - 1;
 
      let i = 0;
      for (; i < l; i++) {
        try {
          stream.emit('log', JSON.parse(data[i]));
        } catch (e) {
          stream.emit('error', e);
        }
      }
 
      buff = data[l];
    });
    req.on('error', err => stream.emit('error', err));
 
    return stream;
  }
 
  /**
   * Make a request to a winstond server or any http server which can
   * handle json-rpc.
   * @param {function} options - Options to sent the request.
   * @param {Object?} auth - authentication options
   * @param {string} path - request path
   * @param {function} callback - Continuation to respond to when complete.
   */
  _request(options, auth, path, callback) {
    options = options || {};
 
    auth = auth || this.auth;
    path = path || this.path || '';
 
    if (this.batch) {
      this._doBatch(options, callback, auth, path);
    } else {
      this._doRequest(options, callback, auth, path);
    }
  }
 
  /**
   * Send or memorize the options according to batch configuration
   * @param {function} options - Options to sent the request.
   * @param {function} callback - Continuation to respond to when complete.
   * @param {Object?} auth - authentication options
   * @param {string} path - request path
   */
  _doBatch(options, callback, auth, path) {
    this.batchOptions.push(options);
    if (this.batchOptions.length === 1) {
      // First message stored, it's time to start the timeout!
      const me = this;
      this.batchCallback = callback;
      this.batchTimeoutID = setTimeout(function () {
        // timeout is reached, send all messages to endpoint
        me.batchTimeoutID = -1;
        me._doBatchRequest(me.batchCallback, auth, path);
      }, this.batchInterval);
    }
    if (this.batchOptions.length === this.batchCount) {
      // max batch count is reached, send all messages to endpoint
      this._doBatchRequest(this.batchCallback, auth, path);
    }
  }
 
  /**
   * Initiate a request with the memorized batch options, stop the batch timeout
   * @param {function} callback - Continuation to respond to when complete.
   * @param {Object?} auth - authentication options
   * @param {string} path - request path
   */
  _doBatchRequest(callback, auth, path) {
    if (this.batchTimeoutID > 0) {
      clearTimeout(this.batchTimeoutID);
      this.batchTimeoutID = -1;
    }
    const batchOptionsCopy = this.batchOptions.slice();
    this.batchOptions = [];
    this._doRequest(batchOptionsCopy, callback, auth, path);
  }
 
  /**
   * Make a request to a winstond server or any http server which can
   * handle json-rpc.
   * @param {function} options - Options to sent the request.
   * @param {function} callback - Continuation to respond to when complete.
   * @param {Object?} auth - authentication options
   * @param {string} path - request path
   */
  _doRequest(options, callback, auth, path) {
    // Prepare options for outgoing HTTP request
    const headers = Object.assign({}, this.headers);
    if (auth && auth.bearer) {
      headers.Authorization = `Bearer ${auth.bearer}`;
    }
    const req = (this.ssl ? https : http).request({
      ...this.options,
      method: 'POST',
      host: this.host,
      port: this.port,
      path: `/${path.replace(/^\//, '')}`,
      headers: headers,
      auth: (auth && auth.username && auth.password) ? (`${auth.username}:${auth.password}`) : '',
      agent: this.agent
    });
 
    req.on('error', callback);
    req.on('response', res => (
      res.on('end', () => callback(null, res)).resume()
    ));
    const jsonStringify = configure({
      ...(this.maximumDepth && { maximumDepth: this.maximumDepth })
    });
    req.end(Buffer.from(jsonStringify(options, this.options.replacer), 'utf8'));
  }
};