<commit_before>transport = require('./transport')
utils = require('./utils')

class XhrPollingReceiver extends transport.ResponseReceiver
    protocol: "xhr"

    doSendFrame: (payload) ->
        if @session
            @session.unregister()
        if payload isnt 'o'
            r = super(payload + '\n')
            @didClose()
            return r
        else
            # On purpose, after the first response 'o', wait a while
            # before closing a connection. This will allow sockjs to
            # detect if the browser has xhr-streaming capabilities.
            # Opera delivers XHR onreadystatechange signal 3 only once,
            # thus the need to send two zeroes.
            write = (payload) =>
                try
                    return @response.write(payload + '\n')
                catch x
                return  true
            ondrain = =>
                @response.connection.removeListener('drain', ondrain)
                utils.timeout_chain([
                    [150, => write("o")],
                    [150, => write(""); @didClose()],
                ])
            # IE requires 2KB prefix, thus waiting on ondrain
            r = write(Array(2048).join('h') + '\n')
            if r is false
                @response.connection.addListener('drain', ondrain)
            else
                ondrain()
            return true


class XhrStreamingReceiver extends transport.ResponseReceiver
    protocol: "xhr"
    max_response_size: 128*1024

    doSendFrame: (payload) ->
        return super(payload + '\n')


exports.app =
    xhr_poll: (req, res, _, next_filter) ->
        res.setHeader('Content-Type', 'application/javascript; charset=UTF-8')
        res.writeHead(200)

        session = transport.Session.bySessionIdOrNew(req.session,
                                                     req.sockjs_server)
        session.register( new XhrPollingReceiver(res) )
        return true

    xhr_options: (req, res) ->
        res.statusCode = 204    # No content
        res.setHeader('Allow', 'OPTIONS, POST')
        res.setHeader('Access-Control-Max-Age', res.cache_for)
        return ''

    xhr_send: (req, res, data) ->
        if not data
            throw {
                status: 500
                message: 'payload expected'
            }
        d = JSON.parse(data)
        if not d or d.__proto__.constructor isnt Array
            throw {
                status: 500
                message: 'payload expected'
            }
        jsonp = transport.Session.bySessionId(req.session)
        if not jsonp
            throw {status: 404}
        for message in d
            jsonp.didMessage(message)

        # FF assumes that the response is XML.
        res.setHeader('Content-Type', 'text/plain')
        res.writeHead(204)
        res.end()
        return true

    xhr_cors: (req, res, content) ->
        origin = req.headers['origin'] or '*'
        res.setHeader('Access-Control-Allow-Origin', origin)
        headers = req.headers['access-control-request-headers']
        if headers
            res.setHeader('Access-Control-Allow-Headers', headers)
        res.setHeader('Access-Control-Allow-Credentials', 'true')
        return content

    xhr_streaming: (req, res, _, next_filter) ->
        res.setHeader('Content-Type', 'application/javascript; charset=UTF-8')
        res.writeHead(200)

        # IE requires 2KB prefix:
        #  http://blogs.msdn.com/b/ieinternals/archive/2010/04/06/comet-streaming-in-internet-explorer-with-xmlhttprequest-and-xdomainrequest.aspx
        res.write(Array(2048).join('h') + '\n')

        session = transport.Session.bySessionIdOrNew(req.session,
                                                     req.sockjs_server)
        session.register( new XhrStreamingReceiver(res) )
        return true<commit_msg>Greatly reduce the server complexity of xhr-polling, in the end it's just a simplified version of xhr-streaming.<commit_after>transport = require('./transport')
utils = require('./utils')

class XhrStreamingReceiver extends transport.ResponseReceiver
    protocol: "xhr-streaming"
    max_response_size: 128*1024

    doSendFrame: (payload) ->
        return super(payload + '\n')

class XhrPollingReceiver extends XhrStreamingReceiver
    protocol: "xhr"
    max_response_size: 1


exports.app =
    xhr_options: (req, res) ->
        res.statusCode = 204    # No content
        res.setHeader('Allow', 'OPTIONS, POST')
        res.setHeader('Access-Control-Max-Age', res.cache_for)
        return ''

    xhr_send: (req, res, data) ->
        if not data
            throw {
                status: 500
                message: 'payload expected'
            }
        d = JSON.parse(data)
        if not d or d.__proto__.constructor isnt Array
            throw {
                status: 500
                message: 'payload expected'
            }
        jsonp = transport.Session.bySessionId(req.session)
        if not jsonp
            throw {status: 404}
        for message in d
            jsonp.didMessage(message)

        # FF assumes that the response is XML.
        res.setHeader('Content-Type', 'text/plain')
        res.writeHead(204)
        res.end()
        return true

    xhr_cors: (req, res, content) ->
        origin = req.headers['origin'] or '*'
        res.setHeader('Access-Control-Allow-Origin', origin)
        headers = req.headers['access-control-request-headers']
        if headers
            res.setHeader('Access-Control-Allow-Headers', headers)
        res.setHeader('Access-Control-Allow-Credentials', 'true')
        return content

    xhr_poll: (req, res, _, next_filter) ->
        res.setHeader('Content-Type', 'application/javascript; charset=UTF-8')
        res.writeHead(200)

        session = transport.Session.bySessionIdOrNew(req.session,
                                                     req.sockjs_server)
        session.register( new XhrPollingReceiver(res) )
        return true

    xhr_streaming: (req, res, _, next_filter) ->
        res.setHeader('Content-Type', 'application/javascript; charset=UTF-8')
        res.writeHead(200)

        # IE requires 2KB prefix:
        #  http://blogs.msdn.com/b/ieinternals/archive/2010/04/06/comet-streaming-in-internet-explorer-with-xmlhttprequest-and-xdomainrequest.aspx
        res.write(Array(2048).join('h') + '\n')

        session = transport.Session.bySessionIdOrNew(req.session,
                                                     req.sockjs_server)
        session.register( new XhrStreamingReceiver(res) )
        return true
{'fraction_non_alphanumeric': 0.1067577828397874, 'fraction_numerical': 0.015034168564920273, 'mean_word_length': 1.8747271933653427, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 20, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 2}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3266200', 'n_tokens_mistral': 1911, 'n_tokens_neox': 1772, 'n_words': 412}