<commit_before>import http from 'http'
import WS from 'ws'

import app from './app'
import config from '../config'
import backup from './backup'
import store from './store'
import { getConnection, storeDocument, findDocuments } from './storage'

const port = process.env.PORT || config.port
app.set('port', port)

const server = http.createServer(app)
server.on('error', (err) => console.log(`Could not start server: ${err}`))

const wss = new WS.Server({ server })

if (config.backup) {
  backup.start()
}

// Load stored actions
findDocuments({ collection: 'actions' })
  .then((actions) => actions.forEach((action) => store.dispatch(action)))

wss.on('connection', (ws) => {
  ws.send(JSON.stringify(store.getState()))

  ws.on('message', (msg) => {
    const action = JSON.parse(msg)
    storeDocument({ collection: 'actions', document: action }).then(() => {
      store.dispatch(action)
      wss.clients.forEach((ws) => ws.send(JSON.stringify(store.getState())))
    }).catch((err) => console.log(`Could not save ${action} due to ${err}`))
  })
})

export function listen (cb) {
  server.on('listening', () => {
    console.log(`Listening on port ${port}`)<commit_msg>Improve error message<commit_after>import http from 'http'
import WS from 'ws'

import app from './app'
import config from '../config'
import backup from './backup'
import store from './store'
import { getConnection, storeDocument, findDocuments } from './storage'

const port = process.env.PORT || config.port
app.set('port', port)

const server = http.createServer(app)
server.on('error', (err) => console.log(`Could not start server: ${err}`))

const wss = new WS.Server({ server })

if (config.backup) {
  backup.start()
}

// Load stored actions
findDocuments({ collection: 'actions' })
  .then((actions) => actions.forEach((action) => store.dispatch(action)))

wss.on('connection', (ws) => {
  ws.send(JSON.stringify(store.getState()))

  ws.on('message', (msg) => {
    const action = JSON.parse(msg)
    storeDocument({ collection: 'actions', document: action }).then(() => {
      store.dispatch(action)
      wss.clients.forEach((ws) => ws.send(JSON.stringify(store.getState())))
    }).catch((err) => console.log(`Could not save ${JSON.stringify(action)} due to ${err}`))
  })
})

export function listen (cb) {
  server.on('listening', () => {
    console.log(`Listening on port ${port}`)
{'fraction_non_alphanumeric': 0.18744734625105308, 'fraction_numerical': 0.0, 'mean_word_length': 4.422374429223744, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 21, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1259842', 'n_tokens_mistral': 749, 'n_tokens_neox': 735, 'n_words': 195}