ASpellWorker.js 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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 OError = require('@overleaf/o-error')
  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 OError({
  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 OError({
  83. message: 'aspell worker error',
  84. info: errInfo
  85. }).withCause(err),
  86. []
  87. )
  88. this.callback = null
  89. } else {
  90. logger.warn(
  91. Object.assign({ error: err }, errInfo),
  92. 'aspell worker error'
  93. )
  94. }
  95. })
  96. this.pipe.stdin.on('error', err => {
  97. const previousWorkerState = this.state
  98. if (this.state !== 'killed') {
  99. this.state = 'error'
  100. }
  101. const errInfo = {
  102. process: this.pipe.pid,
  103. stdout: output.slice(-1024),
  104. stderr: error.slice(-1024),
  105. lang: this.language,
  106. workerState: this.state,
  107. previousWorkerState,
  108. closeReason: this.closeReason
  109. }
  110. if (this.callback != null) {
  111. this.callback(
  112. new OError({
  113. message: 'aspell worker error on stdin',
  114. info: errInfo
  115. }).withCause(err),
  116. []
  117. )
  118. this.callback = null
  119. } else {
  120. logger.warn(
  121. Object.assign({ error: err }, errInfo),
  122. 'aspell worker error on stdin'
  123. )
  124. }
  125. })
  126. this.pipe.stdout.setEncoding('utf8') // ensure utf8 output is handled correctly
  127. var output = ''
  128. const endMarkerRegex = new RegExp('^[a-z][a-z]', 'gm')
  129. this.pipe.stdout.on('data', data => {
  130. // We receive the language code from Aspell as the end of data marker in
  131. // the data. The input is a utf8 encoded string.
  132. const oldPos = output.length
  133. output = output + data
  134. // The end marker may cross the end of a chunk, so we optimise the search
  135. // using the regex lastIndex property.
  136. endMarkerRegex.lastIndex = oldPos > 2 ? oldPos - 2 : 0
  137. if (endMarkerRegex.test(output)) {
  138. if (this.callback != null) {
  139. this.callback(null, output.slice())
  140. this.callback = null // only allow one callback in use
  141. } else {
  142. logger.err(
  143. {
  144. process: this.pipe.pid,
  145. lang: this.language,
  146. workerState: this.state
  147. },
  148. 'end of data marker received when callback already used'
  149. )
  150. }
  151. this.state = 'ready'
  152. output = ''
  153. }
  154. })
  155. var error = ''
  156. this.pipe.stderr.on('data', chunk => {
  157. return (error = error + chunk)
  158. })
  159. this.pipe.stdout.on('end', () => {
  160. // process has ended
  161. return (this.state = 'end')
  162. })
  163. }
  164. isReady() {
  165. return this.state === 'ready'
  166. }
  167. check(words, callback) {
  168. // we will now send data to aspell, and be ready again when we
  169. // receive the end of data marker
  170. this.state = 'busy'
  171. if (this.callback != null) {
  172. // only allow one callback in use
  173. return this.callback(
  174. new OError({
  175. message: 'Aspell callback already in use - SHOULD NOT HAPPEN',
  176. info: {
  177. process: this.pipe.pid,
  178. lang: this.language,
  179. workerState: this.state
  180. }
  181. })
  182. )
  183. }
  184. this.callback = _.once(callback) // extra defence against double callback
  185. this.setTerseMode()
  186. this.write(words)
  187. return this.flush()
  188. }
  189. write(words) {
  190. let i = 0
  191. return (() => {
  192. const result = []
  193. while (i < words.length) {
  194. // batch up the words to check for efficiency
  195. const batch = words.slice(i, i + BATCH_SIZE)
  196. this.sendWords(batch)
  197. result.push((i += BATCH_SIZE))
  198. }
  199. return result
  200. })()
  201. }
  202. flush() {
  203. // get aspell to send an end of data marker "*" when ready
  204. // @sendCommand("%") # take the aspell pipe out of terse mode so we can look for a '*'
  205. // @sendCommand("^ENDOFSTREAMMARKER") # send our marker which will generate a '*'
  206. // @sendCommand("!") # go back into terse mode
  207. return this.sendCommand('$$l')
  208. }
  209. shutdown(reason) {
  210. logger.info({ process: this.pipe.pid, reason }, 'shutting down')
  211. this.state = 'closing'
  212. this.closeReason = reason
  213. return this.pipe.stdin.end()
  214. }
  215. kill(reason) {
  216. logger.info({ process: this.pipe.pid, reason }, 'killing')
  217. this.closeReason = reason
  218. if (this.state === 'killed') {
  219. return
  220. }
  221. return this.pipe.kill('SIGKILL')
  222. }
  223. setTerseMode() {
  224. return this.sendCommand('!')
  225. }
  226. sendWord(word) {
  227. return this.sendCommand(`^${word}`)
  228. }
  229. sendWords(words) {
  230. // Aspell accepts multiple words to check on the same line
  231. // ^word1 word2 word3 ...
  232. // See aspell.info, writing programs to use Aspell Through A Pipe
  233. this.sendCommand(`^${words.join(' ')}`)
  234. return this.count++
  235. }
  236. sendCommand(command) {
  237. return this.pipe.stdin.write(command + '\n')
  238. }
  239. }
  240. module.exports = ASpellWorker