ASpell.js 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. // TODO: This file was created by bulk-decaffeinate.
  2. // Sanity-check the conversion and remove this comment.
  3. /*
  4. * decaffeinate suggestions:
  5. * DS101: Remove unnecessary use of Array.from
  6. * DS102: Remove unnecessary code created because of implicit returns
  7. * DS207: Consider shorter variations of null checks
  8. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  9. */
  10. let ASpell
  11. const ASpellWorkerPool = require('./ASpellWorkerPool')
  12. const LRU = require('lru-cache')
  13. const logger = require('logger-sharelatex')
  14. const fs = require('fs')
  15. const settings = require('settings-sharelatex')
  16. const Path = require('path')
  17. const OneMinute = 60 * 1000
  18. const opts = { max: 10000, maxAge: OneMinute * 60 * 10 }
  19. const cache = LRU(opts)
  20. const cacheFsPath = Path.resolve(settings.cacheDir, 'spell.cache')
  21. const cacheFsPathTmp = cacheFsPath + '.tmp'
  22. // load any existing cache
  23. try {
  24. const oldCache = fs.readFileSync(cacheFsPath)
  25. cache.load(JSON.parse(oldCache))
  26. } catch (error) {
  27. const err = error
  28. logger.log({ err, cacheFsPath }, 'could not load the cache file')
  29. }
  30. // write the cache every 30 minutes
  31. setInterval(function() {
  32. const dump = JSON.stringify(cache.dump())
  33. return fs.writeFile(cacheFsPathTmp, dump, function(err) {
  34. if (err != null) {
  35. logger.log({ err }, 'error writing cache file')
  36. return fs.unlink(cacheFsPathTmp)
  37. } else {
  38. fs.rename(cacheFsPathTmp, cacheFsPath)
  39. return logger.log({ len: dump.length, cacheFsPath }, 'wrote cache file')
  40. }
  41. })
  42. }, 30 * OneMinute)
  43. class ASpellRunner {
  44. checkWords(language, words, callback) {
  45. if (callback == null) {
  46. callback = () => {}
  47. }
  48. return this.runAspellOnWords(language, words, (error, output) => {
  49. if (error != null) {
  50. return callback(error)
  51. }
  52. // output = @removeAspellHeader(output)
  53. const suggestions = this.getSuggestions(language, output)
  54. const results = []
  55. let hits = 0
  56. const addToCache = {}
  57. for (let i = 0; i < words.length; i++) {
  58. const word = words[i]
  59. const key = language + ':' + word
  60. const cached = cache.get(key)
  61. if (cached != null) {
  62. hits++
  63. if (cached === true) {
  64. // valid word, no need to do anything
  65. continue
  66. } else {
  67. results.push({ index: i, suggestions: cached })
  68. }
  69. } else {
  70. if (suggestions[key] != null) {
  71. addToCache[key] = suggestions[key]
  72. results.push({ index: i, suggestions: suggestions[key] })
  73. } else {
  74. // a valid word, but uncached
  75. addToCache[key] = true
  76. }
  77. }
  78. }
  79. // update the cache after processing all words, to avoid cache
  80. // changing while we use it
  81. for (let k in addToCache) {
  82. const v = addToCache[k]
  83. cache.set(k, v)
  84. }
  85. logger.info(
  86. {
  87. hits,
  88. total: words.length,
  89. hitrate: (hits / words.length).toFixed(2)
  90. },
  91. 'cache hit rate'
  92. )
  93. return callback(null, results)
  94. })
  95. }
  96. getSuggestions(language, output) {
  97. const lines = output.split('\n')
  98. const suggestions = {}
  99. for (let line of Array.from(lines)) {
  100. var parts, word
  101. if (line[0] === '&') {
  102. // Suggestions found
  103. parts = line.split(' ')
  104. if (parts.length > 1) {
  105. word = parts[1]
  106. const suggestionsString = line.slice(line.indexOf(':') + 2)
  107. suggestions[language + ':' + word] = suggestionsString.split(', ')
  108. }
  109. } else if (line[0] === '#') {
  110. // No suggestions
  111. parts = line.split(' ')
  112. if (parts.length > 1) {
  113. word = parts[1]
  114. suggestions[language + ':' + word] = []
  115. }
  116. }
  117. }
  118. return suggestions
  119. }
  120. // removeAspellHeader: (output) -> output.slice(1)
  121. runAspellOnWords(language, words, callback) {
  122. // send words to aspell, get back string output for those words
  123. // find a free pipe for the language (or start one)
  124. // send the words down the pipe
  125. // send an END marker that will generate a "*" line in the output
  126. // when the output pipe receives the "*" return the data sofar and reset the pipe to be available
  127. //
  128. // @open(language)
  129. // @captureOutput(callback)
  130. // @setTerseMode()
  131. // start = new Date()
  132. if (callback == null) {
  133. callback = () => {}
  134. }
  135. const newWord = {}
  136. for (let word of Array.from(words)) {
  137. if (!newWord[word] && !cache.has(language + ':' + word)) {
  138. newWord[word] = true
  139. }
  140. }
  141. words = Object.keys(newWord)
  142. if (words.length) {
  143. return WorkerPool.check(language, words, ASpell.ASPELL_TIMEOUT, callback)
  144. } else {
  145. return callback(null, '')
  146. }
  147. }
  148. }
  149. module.exports = ASpell = {
  150. // The description of how to call aspell from another program can be found here:
  151. // http://aspell.net/man-html/Through-A-Pipe.html
  152. checkWords(language, words, callback) {
  153. if (callback == null) {
  154. callback = () => {}
  155. }
  156. const runner = new ASpellRunner()
  157. return runner.checkWords(language, words, callback)
  158. },
  159. ASPELL_TIMEOUT: 4000
  160. }
  161. var WorkerPool = new ASpellWorkerPool()