ASpellWorker.js 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. // TODO: This file was created by bulk-decaffeinate.
  2. // Sanity-check the conversion and remove this comment.
  3. /*
  4. * decaffeinate suggestions:
  5. * DS102: Remove unnecessary code created because of implicit returns
  6. * DS205: Consider reworking code to avoid use of IIFEs
  7. * DS207: Consider shorter variations of null checks
  8. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  9. */
  10. const childProcess = require('child_process')
  11. const logger = require('logger-sharelatex')
  12. const metrics = require('metrics-sharelatex')
  13. const _ = require('underscore')
  14. const errorType = require('overleaf-error-type')
  15. const BATCH_SIZE = 100
  16. class ASpellWorker {
  17. constructor(language) {
  18. this.language = language
  19. this.count = 0
  20. this.closeReason = ''
  21. this.pipe = childProcess.spawn('aspell', [
  22. 'pipe',
  23. '-t',
  24. '--encoding=utf-8',
  25. '-d',
  26. language
  27. ])
  28. logger.info(
  29. { process: this.pipe.pid, lang: this.language },
  30. 'starting new aspell worker'
  31. )
  32. metrics.inc('aspellWorker', 1, { status: 'start', method: this.language })
  33. this.pipe.on('exit', () => {
  34. this.state = 'killed'
  35. logger.info(
  36. { process: this.pipe.pid, lang: this.language },
  37. 'aspell worker has exited'
  38. )
  39. metrics.inc('aspellWorker', 1, {
  40. status: 'exit',
  41. method: this.language
  42. })
  43. })
  44. this.pipe.on('close', () => {
  45. const previousWorkerState = this.state
  46. if (this.state !== 'killed') {
  47. this.state = 'closed'
  48. }
  49. if (this.callback != null) {
  50. const err = new errorType.Error({
  51. message: 'aspell worker closed output streams with uncalled callback',
  52. info: {
  53. process: this.pipe.pid,
  54. lang: this.language,
  55. stdout: output.slice(-1024),
  56. stderr: error.slice(-1024),
  57. workerState: this.state,
  58. previousWorkerState,
  59. closeReason: this.closeReason
  60. }
  61. })
  62. this.callback(err, [])
  63. this.callback = null
  64. }
  65. })
  66. this.pipe.on('error', err => {
  67. const previousWorkerState = this.state
  68. if (this.state !== 'killed') {
  69. this.state = 'error'
  70. }
  71. const errInfo = {
  72. process: this.pipe.pid,
  73. stdout: output.slice(-1024),
  74. stderr: error.slice(-1024),
  75. lang: this.language,
  76. workerState: this.state,
  77. previousWorkerState,
  78. closeReason: this.closeReason
  79. }
  80. if (this.callback != null) {
  81. this.callback(
  82. new errorType.Error({
  83. message: 'aspell worker error',
  84. info: errInfo
  85. }).withCause(err),
  86. []
  87. )
  88. this.callback = null
  89. } else {
  90. logger.warn({ error: err, ...errInfo }, 'aspell worker error')
  91. }
  92. })
  93. this.pipe.stdin.on('error', err => {
  94. const previousWorkerState = this.state
  95. if (this.state !== 'killed') {
  96. this.state = 'error'
  97. }
  98. const errInfo = {
  99. process: this.pipe.pid,
  100. stdout: output.slice(-1024),
  101. stderr: error.slice(-1024),
  102. lang: this.language,
  103. workerState: this.state,
  104. previousWorkerState,
  105. closeReason: this.closeReason
  106. }
  107. if (this.callback != null) {
  108. this.callback(
  109. new errorType.Error({
  110. message: 'aspell worker error on stdin',
  111. info: errInfo
  112. }).withCause(err),
  113. []
  114. )
  115. this.callback = null
  116. } else {
  117. logger.warn(
  118. {
  119. error: err,
  120. ...errInfo
  121. },
  122. 'aspell worker error on stdin'
  123. )
  124. }
  125. })
  126. var output = ''
  127. const endMarker = new RegExp('^[a-z][a-z]', 'm')
  128. this.pipe.stdout.on('data', chunk => {
  129. output = output + chunk
  130. // We receive the language code from Aspell as the end of data marker
  131. if (chunk.toString().match(endMarker)) {
  132. if (this.callback != null) {
  133. this.callback(null, output.slice())
  134. this.callback = null // only allow one callback in use
  135. } else {
  136. logger.err(
  137. {
  138. process: this.pipe.pid,
  139. lang: this.language,
  140. workerState: this.state
  141. },
  142. 'end of data marker received when callback already used'
  143. )
  144. }
  145. this.state = 'ready'
  146. output = ''
  147. }
  148. })
  149. var error = ''
  150. this.pipe.stderr.on('data', chunk => {
  151. return (error = error + chunk)
  152. })
  153. this.pipe.stdout.on('end', () => {
  154. // process has ended
  155. return (this.state = 'end')
  156. })
  157. }
  158. isReady() {
  159. return this.state === 'ready'
  160. }
  161. check(words, callback) {
  162. // we will now send data to aspell, and be ready again when we
  163. // receive the end of data marker
  164. this.state = 'busy'
  165. if (this.callback != null) {
  166. // only allow one callback in use
  167. return this.callback(
  168. new errorType.Error({
  169. message: 'Aspell callback already in use - SHOULD NOT HAPPEN',
  170. info: {
  171. process: this.pipe.pid,
  172. lang: this.language,
  173. workerState: this.state
  174. }
  175. })
  176. )
  177. }
  178. this.callback = _.once(callback) // extra defence against double callback
  179. this.setTerseMode()
  180. this.write(words)
  181. return this.flush()
  182. }
  183. write(words) {
  184. let i = 0
  185. return (() => {
  186. const result = []
  187. while (i < words.length) {
  188. // batch up the words to check for efficiency
  189. const batch = words.slice(i, i + BATCH_SIZE)
  190. this.sendWords(batch)
  191. result.push((i += BATCH_SIZE))
  192. }
  193. return result
  194. })()
  195. }
  196. flush() {
  197. // get aspell to send an end of data marker "*" when ready
  198. // @sendCommand("%") # take the aspell pipe out of terse mode so we can look for a '*'
  199. // @sendCommand("^ENDOFSTREAMMARKER") # send our marker which will generate a '*'
  200. // @sendCommand("!") # go back into terse mode
  201. return this.sendCommand('$$l')
  202. }
  203. shutdown(reason) {
  204. logger.info({ process: this.pipe.pid, reason }, 'shutting down')
  205. this.state = 'closing'
  206. this.closeReason = reason
  207. return this.pipe.stdin.end()
  208. }
  209. kill(reason) {
  210. logger.info({ process: this.pipe.pid, reason }, 'killing')
  211. this.closeReason = reason
  212. if (this.state === 'killed') {
  213. return
  214. }
  215. return this.pipe.kill('SIGKILL')
  216. }
  217. setTerseMode() {
  218. return this.sendCommand('!')
  219. }
  220. sendWord(word) {
  221. return this.sendCommand(`^${word}`)
  222. }
  223. sendWords(words) {
  224. // Aspell accepts multiple words to check on the same line
  225. // ^word1 word2 word3 ...
  226. // See aspell.info, writing programs to use Aspell Through A Pipe
  227. this.sendCommand(`^${words.join(' ')}`)
  228. return this.count++
  229. }
  230. sendCommand(command) {
  231. return this.pipe.stdin.write(command + '\n')
  232. }
  233. }
  234. module.exports = ASpellWorker