index.js 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. const { Writable, Readable, PassThrough, Transform } = require('node:stream')
  2. /**
  3. * A writable stream that stores all data written to it in a node Buffer.
  4. * @extends Writable
  5. * @example
  6. * const { WritableBuffer } = require('@overleaf/stream-utils')
  7. * const bufferStream = new WritableBuffer()
  8. * bufferStream.write('hello')
  9. * bufferStream.write('world')
  10. * bufferStream.end()
  11. * bufferStream.contents().toString() // 'helloworld'
  12. */
  13. class WritableBuffer extends Writable {
  14. constructor(options) {
  15. super(options)
  16. this._buffers = []
  17. this._size = 0
  18. }
  19. _write(chunk, encoding, callback) {
  20. this._buffers.push(chunk)
  21. this._size += chunk.length
  22. callback()
  23. }
  24. _final(callback) {
  25. callback()
  26. }
  27. size() {
  28. return this._size
  29. }
  30. getContents() {
  31. return Buffer.concat(this._buffers)
  32. }
  33. contents() {
  34. return Buffer.concat(this._buffers)
  35. }
  36. }
  37. /**
  38. * A readable stream created from a string.
  39. * @extends Readable
  40. * @example
  41. * const { ReadableString } = require('@overleaf/stream-utils')
  42. * const stringStream = new ReadableString('hello world')
  43. * stringStream.on('data', chunk => console.log(chunk.toString()))
  44. * stringStream.on('end', () => console.log('done'))
  45. */
  46. class ReadableString extends Readable {
  47. constructor(string, options) {
  48. super(options)
  49. this._string = string
  50. }
  51. _read(size) {
  52. this.push(this._string)
  53. this.push(null)
  54. }
  55. }
  56. class SizeExceededError extends Error {}
  57. /**
  58. * Limited size stream which will emit a SizeExceededError if the size is exceeded
  59. * @extends Transform
  60. */
  61. class LimitedStream extends Transform {
  62. constructor(maxSize) {
  63. super()
  64. this.maxSize = maxSize
  65. this.size = 0
  66. }
  67. _transform(chunk, encoding, callback) {
  68. this.size += chunk.byteLength
  69. if (this.size > this.maxSize) {
  70. callback(
  71. new SizeExceededError(
  72. `exceeded stream size limit of ${this.maxSize}: ${this.size}`
  73. )
  74. )
  75. } else {
  76. callback(null, chunk)
  77. }
  78. }
  79. }
  80. class AbortError extends Error {}
  81. /**
  82. * TimeoutStream which will emit an AbortError if it exceeds a user specified timeout
  83. * @extends PassThrough
  84. */
  85. class TimeoutStream extends PassThrough {
  86. constructor(timeout) {
  87. super()
  88. this.t = setTimeout(() => {
  89. this.destroy(new AbortError('stream timed out'))
  90. }, timeout)
  91. }
  92. _final(callback) {
  93. clearTimeout(this.t)
  94. callback()
  95. }
  96. }
  97. /**
  98. * LoggerStream which will call the provided logger function when the stream exceeds a user specified limit. It will call the provided function again when flushing the stream and it exceeded the user specified limit before.
  99. * @extends Transform
  100. */
  101. class LoggerStream extends Transform {
  102. /**
  103. * Constructor.
  104. * @param {number} maxSize
  105. * @param {function(currentSizeOfStream: number, isFlush: boolean)} fn
  106. * @param {Object?} options optional options for the Transform stream
  107. */
  108. constructor(maxSize, fn, options) {
  109. super(options)
  110. this.fn = fn
  111. this.size = 0
  112. this.maxSize = maxSize
  113. this.logged = false
  114. }
  115. _transform(chunk, encoding, callback) {
  116. this.size += chunk.byteLength
  117. if (this.size > this.maxSize && !this.logged) {
  118. this.fn(this.size)
  119. this.logged = true
  120. }
  121. callback(null, chunk)
  122. }
  123. _flush(callback) {
  124. if (this.size > this.maxSize) {
  125. this.fn(this.size, true)
  126. }
  127. callback()
  128. }
  129. }
  130. class MeteredStream extends Transform {
  131. #Metrics
  132. #metric
  133. #labels
  134. constructor(Metrics, metric, labels) {
  135. super()
  136. this.#Metrics = Metrics
  137. this.#metric = metric
  138. this.#labels = labels
  139. }
  140. _transform(chunk, encoding, callback) {
  141. this.#Metrics.count(this.#metric, chunk.byteLength, 1, this.#labels)
  142. callback(null, chunk)
  143. }
  144. }
  145. class IncrementalResponse {
  146. #res
  147. #ac
  148. #timeout
  149. #logger
  150. #label
  151. #info
  152. constructor({ res, timeout, label, info, logger }) {
  153. this.#res = res
  154. this.#logger = logger
  155. this.#label = label
  156. this.#info = info
  157. this.#ac = new AbortController()
  158. this.#timeout = setTimeout(() => {
  159. this.#logger.warn({ ...this.#info, timeout }, `${this.#label}: aborting`)
  160. this.sendUpdate(
  161. `error: ${label}: aborting after ${this.#humanReadableTimeout(timeout)}`
  162. )
  163. this.#ac.abort()
  164. }, timeout)
  165. }
  166. signal() {
  167. return this.#ac.signal
  168. }
  169. end() {
  170. this.#ac.abort()
  171. clearTimeout(this.#timeout)
  172. try {
  173. this.#res.end()
  174. } catch {
  175. try {
  176. this.#res.destroy()
  177. } catch {}
  178. }
  179. }
  180. sendUpdate(msg) {
  181. try {
  182. this.#res.write(msg + '\n')
  183. } catch (err) {
  184. this.#ac.abort()
  185. this.#logger.warn(
  186. { err, ...this.#info },
  187. `${this.#label}: failed to send progress update`
  188. )
  189. }
  190. }
  191. fail(err) {
  192. const aborted = this.#ac.signal.aborted
  193. this.#ac.abort()
  194. if (!aborted) {
  195. this.#logger.err({ err, ...this.#info }, `${this.#label}: error`)
  196. this.sendUpdate(`error: ${this.#label}`)
  197. }
  198. this.end()
  199. }
  200. #humanReadableTimeout(timeout) {
  201. let ms = timeout
  202. const minutes = Math.floor(ms / 60_000)
  203. ms -= minutes * 60_000
  204. const seconds = Math.floor(ms / 1_000)
  205. ms -= seconds * 1_000
  206. let t = ''
  207. if (minutes) t += `${minutes}min`
  208. if (seconds) t += `${seconds}s`
  209. if (ms) t += `${ms}ms`
  210. return t
  211. }
  212. }
  213. // Export our classes
  214. module.exports = {
  215. WritableBuffer,
  216. ReadableString,
  217. LoggerStream,
  218. LimitedStream,
  219. TimeoutStream,
  220. MeteredStream,
  221. SizeExceededError,
  222. AbortError,
  223. IncrementalResponse,
  224. }