{
    "file_diffs": [
        {
            "old_file_content": "#!/usr/bin/env python\n#\n# Copyright 2011 Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"A non-blocking, single-threaded TCP server.\"\"\"\nfrom __future__ import absolute_import, division, print_function, with_statement\n\nimport errno\nimport os\nimport socket\n\nfrom tornado.log import app_log\nfrom tornado.ioloop import IOLoop\nfrom tornado.iostream import IOStream, SSLIOStream\nfrom tornado.netutil import bind_sockets, add_accept_handler, ssl_wrap_socket\nfrom tornado import process\nfrom tornado.util import errno_from_exception\n\ntry:\n    import ssl\nexcept ImportError:\n    # ssl is not available on Google App Engine.\n    ssl = None\n\n\nclass TCPServer(object):\n    r\"\"\"A non-blocking, single-threaded TCP server.\n\n    To use `TCPServer`, define a subclass which overrides the `handle_stream`\n    method. For example, a simple echo server could be defined like this::\n\n      from tornado.tcpserver import TCPServer\n      from tornado.iostream import StreamClosedError\n      from tornado import gen\n\n      class EchoServer(TCPServer):\n          @gen.coroutine\n          def handle_stream(self, stream, address):\n              while True:\n                  try:\n                      data = yield stream.read_until(b\"\\n\")\n                      yield stream.write(data)\n                  except StreamClosedError:\n                      break\n\n    To make this server serve SSL traffic, send the ``ssl_options`` keyword\n    argument with an `ssl.SSLContext` object. For compatibility with older\n    versions of Python ``ssl_options`` may also be a dictionary of keyword\n    arguments for the `ssl.wrap_socket` method.::\n\n       ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)\n       ssl_ctx.load_cert_chain(os.path.join(data_dir, \"mydomain.crt\"),\n                               os.path.join(data_dir, \"mydomain.key\"))\n       TCPServer(ssl_options=ssl_ctx)\n\n    `TCPServer` initialization follows one of three patterns:\n\n    1. `listen`: simple single-process::\n\n            server = TCPServer()\n            server.listen(8888)\n            IOLoop.current().start()\n\n    2. `bind`/`start`: simple multi-process::\n\n            server = TCPServer()\n            server.bind(8888)\n            server.start(0)  # Forks multiple sub-processes\n            IOLoop.current().start()\n\n       When using this interface, an `.IOLoop` must *not* be passed\n       to the `TCPServer` constructor.  `start` will always start\n       the server on the default singleton `.IOLoop`.\n\n    3. `add_sockets`: advanced multi-process::\n\n            sockets = bind_sockets(8888)\n            tornado.process.fork_processes(0)\n            server = TCPServer()\n            server.add_sockets(sockets)\n            IOLoop.current().start()\n\n       The `add_sockets` interface is more complicated, but it can be\n       used with `tornado.process.fork_processes` to give you more\n       flexibility in when the fork happens.  `add_sockets` can\n       also be used in single-process servers if you want to create\n       your listening sockets in some way other than\n       `~tornado.netutil.bind_sockets`.\n\n    .. versionadded:: 3.1\n       The ``max_buffer_size`` argument.\n    \"\"\"\n    def __init__(self, io_loop=None, ssl_options=None, max_buffer_size=None,\n                 read_chunk_size=None):\n        self.io_loop = io_loop\n        self.ssl_options = ssl_options\n        self._sockets = {}  # fd -> socket object\n        self._pending_sockets = []\n        self._started = False\n        self._stopped = False\n        self.max_buffer_size = max_buffer_size\n        self.read_chunk_size = read_chunk_size\n\n        # Verify the SSL options. Otherwise we don't get errors until clients\n        # connect. This doesn't verify that the keys are legitimate, but\n        # the SSL module doesn't do that until there is a connected socket\n        # which seems like too much work\n        if self.ssl_options is not None and isinstance(self.ssl_options, dict):\n            # Only certfile is required: it can contain both keys\n            if 'certfile' not in self.ssl_options:\n                raise KeyError('missing key \"certfile\" in ssl_options')\n\n            if not os.path.exists(self.ssl_options['certfile']):\n                raise ValueError('certfile \"%s\" does not exist' %\n                                 self.ssl_options['certfile'])\n            if ('keyfile' in self.ssl_options and\n                    not os.path.exists(self.ssl_options['keyfile'])):\n                raise ValueError('keyfile \"%s\" does not exist' %\n                                 self.ssl_options['keyfile'])\n\n    def listen(self, port, address=\"\"):\n        \"\"\"Starts accepting connections on the given port.\n\n        This method may be called more than once to listen on multiple ports.\n        `listen` takes effect immediately; it is not necessary to call\n        `TCPServer.start` afterwards.  It is, however, necessary to start\n        the `.IOLoop`.\n        \"\"\"\n        sockets = bind_sockets(port, address=address)\n        self.add_sockets(sockets)\n\n    def add_sockets(self, sockets):\n        \"\"\"Makes this server start accepting connections on the given sockets.\n\n        The ``sockets`` parameter is a list of socket objects such as\n        those returned by `~tornado.netutil.bind_sockets`.\n        `add_sockets` is typically used in combination with that\n        method and `tornado.process.fork_processes` to provide greater\n        control over the initialization of a multi-process server.\n        \"\"\"\n        if self.io_loop is None:\n            self.io_loop = IOLoop.current()\n\n        for sock in sockets:\n            self._sockets[sock.fileno()] = sock\n            add_accept_handler(sock, self._handle_connection,\n                               io_loop=self.io_loop)\n\n    def add_socket(self, socket):\n        \"\"\"Singular version of `add_sockets`.  Takes a single socket object.\"\"\"\n        self.add_sockets([socket])\n\n    def bind(self, port, address=None, family=socket.AF_UNSPEC, backlog=128,\n             reuse_port=False):\n        \"\"\"Binds this server to the given port on the given address.\n\n        To start the server, call `start`. If you want to run this server\n        in a single process, you can call `listen` as a shortcut to the\n        sequence of `bind` and `start` calls.\n\n        Address may be either an IP address or hostname.  If it's a hostname,\n        the server will listen on all IP addresses associated with the\n        name.  Address may be an empty string or None to listen on all\n        available interfaces.  Family may be set to either `socket.AF_INET`\n        or `socket.AF_INET6` to restrict to IPv4 or IPv6 addresses, otherwise\n        both will be used if available.\n\n        The ``backlog`` argument has the same meaning as for\n        `socket.listen <socket.socket.listen>`. The ``reuse_port`` argument\n        has the same meaning as for `.bind_sockets`.\n\n        This method may be called multiple times prior to `start` to listen\n        on multiple ports or interfaces.\n\n        .. versionchanged:: 4.4\n           Added the ``reuse_port`` argument.\n        \"\"\"\n        sockets = bind_sockets(port, address=address, family=family,\n                               backlog=backlog, reuse_port=reuse_port)\n        if self._started:\n            self.add_sockets(sockets)\n        else:\n            self._pending_sockets.extend(sockets)\n\n    def start(self, num_processes=1):\n        \"\"\"Starts this server in the `.IOLoop`.\n\n        By default, we run the server in this process and do not fork any\n        additional child process.\n\n        If num_processes is ``None`` or <= 0, we detect the number of cores\n        available on this machine and fork that number of child\n        processes. If num_processes is given and > 1, we fork that\n        specific number of sub-processes.\n\n        Since we use processes and not threads, there is no shared memory\n        between any server code.\n\n        Note that multiple processes are not compatible with the autoreload\n        module (or the ``autoreload=True`` option to `tornado.web.Application`\n        which defaults to True when ``debug=True``).\n        When using multiple processes, no IOLoops can be created or\n        referenced until after the call to ``TCPServer.start(n)``.\n        \"\"\"\n        assert not self._started\n        self._started = True\n        if num_processes != 1:\n            process.fork_processes(num_processes)\n        sockets = self._pending_sockets\n        self._pending_sockets = []\n        self.add_sockets(sockets)\n\n    def stop(self):\n        \"\"\"Stops listening for new connections.\n\n        Requests currently in progress may still continue after the\n        server is stopped.\n        \"\"\"\n        if self._stopped:\n            return\n        self._stopped = True\n        for fd, sock in self._sockets.items():\n            assert sock.fileno() == fd\n            self.io_loop.remove_handler(fd)\n            sock.close()\n\n    def handle_stream(self, stream, address):\n        \"\"\"Override to handle a new `.IOStream` from an incoming connection.\n\n        This method may be a coroutine; if so any exceptions it raises\n        asynchronously will be logged. Accepting of incoming connections\n        will not be blocked by this coroutine.\n\n        If this `TCPServer` is configured for SSL, ``handle_stream``\n        may be called before the SSL handshake has completed. Use\n        `.SSLIOStream.wait_for_handshake` if you need to verify the client's\n        certificate or use NPN/ALPN.\n\n        .. versionchanged:: 4.2\n           Added the option for this method to be a coroutine.\n        \"\"\"\n        raise NotImplementedError()\n\n    def _handle_connection(self, connection, address):\n        if self.ssl_options is not None:\n            assert ssl, \"Python 2.6+ and OpenSSL required for SSL\"\n            try:\n                connection = ssl_wrap_socket(connection,\n                                             self.ssl_options,\n                                             server_side=True,\n                                             do_handshake_on_connect=False)\n            except ssl.SSLError as err:\n                if err.args[0] == ssl.SSL_ERROR_EOF:\n                    return connection.close()\n                else:\n                    raise\n            except socket.error as err:\n                # If the connection is closed immediately after it is created\n                # (as in a port scan), we can get one of several errors.\n                # wrap_socket makes an internal call to getpeername,\n                # which may return either EINVAL (Mac OS X) or ENOTCONN\n                # (Linux).  If it returns ENOTCONN, this error is\n                # silently swallowed by the ssl module, so we need to\n                # catch another error later on (AttributeError in\n                # SSLIOStream._do_ssl_handshake).\n                # To test this behavior, try nmap with the -sT flag.\n                # https://github.com/tornadoweb/tornado/pull/750\n                if errno_from_exception(err) in (errno.ECONNABORTED, errno.EINVAL):\n                    return connection.close()\n                else:\n                    raise\n        try:\n            if self.ssl_options is not None:\n                stream = SSLIOStream(connection, io_loop=self.io_loop,\n                                     max_buffer_size=self.max_buffer_size,\n                                     read_chunk_size=self.read_chunk_size)\n            else:\n                stream = IOStream(connection, io_loop=self.io_loop,\n                                  max_buffer_size=self.max_buffer_size,\n                                  read_chunk_size=self.read_chunk_size)\n            future = self.handle_stream(stream, address)\n            if future is not None:\n                self.io_loop.add_future(future, lambda f: f.result())\n        except Exception:\n            app_log.error(\"Error in connection callback\", exc_info=True)\n",
            "new_file_content": "#!/usr/bin/env python\n#\n# Copyright 2011 Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"A non-blocking, single-threaded TCP server.\"\"\"\nfrom __future__ import absolute_import, division, print_function, with_statement\n\nimport errno\nimport os\nimport socket\n\nfrom tornado import gen\nfrom tornado.log import app_log\nfrom tornado.ioloop import IOLoop\nfrom tornado.iostream import IOStream, SSLIOStream\nfrom tornado.netutil import bind_sockets, add_accept_handler, ssl_wrap_socket\nfrom tornado import process\nfrom tornado.util import errno_from_exception\n\ntry:\n    import ssl\nexcept ImportError:\n    # ssl is not available on Google App Engine.\n    ssl = None\n\n\nclass TCPServer(object):\n    r\"\"\"A non-blocking, single-threaded TCP server.\n\n    To use `TCPServer`, define a subclass which overrides the `handle_stream`\n    method. For example, a simple echo server could be defined like this::\n\n      from tornado.tcpserver import TCPServer\n      from tornado.iostream import StreamClosedError\n      from tornado import gen\n\n      class EchoServer(TCPServer):\n          @gen.coroutine\n          def handle_stream(self, stream, address):\n              while True:\n                  try:\n                      data = yield stream.read_until(b\"\\n\")\n                      yield stream.write(data)\n                  except StreamClosedError:\n                      break\n\n    To make this server serve SSL traffic, send the ``ssl_options`` keyword\n    argument with an `ssl.SSLContext` object. For compatibility with older\n    versions of Python ``ssl_options`` may also be a dictionary of keyword\n    arguments for the `ssl.wrap_socket` method.::\n\n       ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)\n       ssl_ctx.load_cert_chain(os.path.join(data_dir, \"mydomain.crt\"),\n                               os.path.join(data_dir, \"mydomain.key\"))\n       TCPServer(ssl_options=ssl_ctx)\n\n    `TCPServer` initialization follows one of three patterns:\n\n    1. `listen`: simple single-process::\n\n            server = TCPServer()\n            server.listen(8888)\n            IOLoop.current().start()\n\n    2. `bind`/`start`: simple multi-process::\n\n            server = TCPServer()\n            server.bind(8888)\n            server.start(0)  # Forks multiple sub-processes\n            IOLoop.current().start()\n\n       When using this interface, an `.IOLoop` must *not* be passed\n       to the `TCPServer` constructor.  `start` will always start\n       the server on the default singleton `.IOLoop`.\n\n    3. `add_sockets`: advanced multi-process::\n\n            sockets = bind_sockets(8888)\n            tornado.process.fork_processes(0)\n            server = TCPServer()\n            server.add_sockets(sockets)\n            IOLoop.current().start()\n\n       The `add_sockets` interface is more complicated, but it can be\n       used with `tornado.process.fork_processes` to give you more\n       flexibility in when the fork happens.  `add_sockets` can\n       also be used in single-process servers if you want to create\n       your listening sockets in some way other than\n       `~tornado.netutil.bind_sockets`.\n\n    .. versionadded:: 3.1\n       The ``max_buffer_size`` argument.\n    \"\"\"\n    def __init__(self, io_loop=None, ssl_options=None, max_buffer_size=None,\n                 read_chunk_size=None):\n        self.io_loop = io_loop\n        self.ssl_options = ssl_options\n        self._sockets = {}  # fd -> socket object\n        self._pending_sockets = []\n        self._started = False\n        self._stopped = False\n        self.max_buffer_size = max_buffer_size\n        self.read_chunk_size = read_chunk_size\n\n        # Verify the SSL options. Otherwise we don't get errors until clients\n        # connect. This doesn't verify that the keys are legitimate, but\n        # the SSL module doesn't do that until there is a connected socket\n        # which seems like too much work\n        if self.ssl_options is not None and isinstance(self.ssl_options, dict):\n            # Only certfile is required: it can contain both keys\n            if 'certfile' not in self.ssl_options:\n                raise KeyError('missing key \"certfile\" in ssl_options')\n\n            if not os.path.exists(self.ssl_options['certfile']):\n                raise ValueError('certfile \"%s\" does not exist' %\n                                 self.ssl_options['certfile'])\n            if ('keyfile' in self.ssl_options and\n                    not os.path.exists(self.ssl_options['keyfile'])):\n                raise ValueError('keyfile \"%s\" does not exist' %\n                                 self.ssl_options['keyfile'])\n\n    def listen(self, port, address=\"\"):\n        \"\"\"Starts accepting connections on the given port.\n\n        This method may be called more than once to listen on multiple ports.\n        `listen` takes effect immediately; it is not necessary to call\n        `TCPServer.start` afterwards.  It is, however, necessary to start\n        the `.IOLoop`.\n        \"\"\"\n        sockets = bind_sockets(port, address=address)\n        self.add_sockets(sockets)\n\n    def add_sockets(self, sockets):\n        \"\"\"Makes this server start accepting connections on the given sockets.\n\n        The ``sockets`` parameter is a list of socket objects such as\n        those returned by `~tornado.netutil.bind_sockets`.\n        `add_sockets` is typically used in combination with that\n        method and `tornado.process.fork_processes` to provide greater\n        control over the initialization of a multi-process server.\n        \"\"\"\n        if self.io_loop is None:\n            self.io_loop = IOLoop.current()\n\n        for sock in sockets:\n            self._sockets[sock.fileno()] = sock\n            add_accept_handler(sock, self._handle_connection,\n                               io_loop=self.io_loop)\n\n    def add_socket(self, socket):\n        \"\"\"Singular version of `add_sockets`.  Takes a single socket object.\"\"\"\n        self.add_sockets([socket])\n\n    def bind(self, port, address=None, family=socket.AF_UNSPEC, backlog=128,\n             reuse_port=False):\n        \"\"\"Binds this server to the given port on the given address.\n\n        To start the server, call `start`. If you want to run this server\n        in a single process, you can call `listen` as a shortcut to the\n        sequence of `bind` and `start` calls.\n\n        Address may be either an IP address or hostname.  If it's a hostname,\n        the server will listen on all IP addresses associated with the\n        name.  Address may be an empty string or None to listen on all\n        available interfaces.  Family may be set to either `socket.AF_INET`\n        or `socket.AF_INET6` to restrict to IPv4 or IPv6 addresses, otherwise\n        both will be used if available.\n\n        The ``backlog`` argument has the same meaning as for\n        `socket.listen <socket.socket.listen>`. The ``reuse_port`` argument\n        has the same meaning as for `.bind_sockets`.\n\n        This method may be called multiple times prior to `start` to listen\n        on multiple ports or interfaces.\n\n        .. versionchanged:: 4.4\n           Added the ``reuse_port`` argument.\n        \"\"\"\n        sockets = bind_sockets(port, address=address, family=family,\n                               backlog=backlog, reuse_port=reuse_port)\n        if self._started:\n            self.add_sockets(sockets)\n        else:\n            self._pending_sockets.extend(sockets)\n\n    def start(self, num_processes=1):\n        \"\"\"Starts this server in the `.IOLoop`.\n\n        By default, we run the server in this process and do not fork any\n        additional child process.\n\n        If num_processes is ``None`` or <= 0, we detect the number of cores\n        available on this machine and fork that number of child\n        processes. If num_processes is given and > 1, we fork that\n        specific number of sub-processes.\n\n        Since we use processes and not threads, there is no shared memory\n        between any server code.\n\n        Note that multiple processes are not compatible with the autoreload\n        module (or the ``autoreload=True`` option to `tornado.web.Application`\n        which defaults to True when ``debug=True``).\n        When using multiple processes, no IOLoops can be created or\n        referenced until after the call to ``TCPServer.start(n)``.\n        \"\"\"\n        assert not self._started\n        self._started = True\n        if num_processes != 1:\n            process.fork_processes(num_processes)\n        sockets = self._pending_sockets\n        self._pending_sockets = []\n        self.add_sockets(sockets)\n\n    def stop(self):\n        \"\"\"Stops listening for new connections.\n\n        Requests currently in progress may still continue after the\n        server is stopped.\n        \"\"\"\n        if self._stopped:\n            return\n        self._stopped = True\n        for fd, sock in self._sockets.items():\n            assert sock.fileno() == fd\n            self.io_loop.remove_handler(fd)\n            sock.close()\n\n    def handle_stream(self, stream, address):\n        \"\"\"Override to handle a new `.IOStream` from an incoming connection.\n\n        This method may be a coroutine; if so any exceptions it raises\n        asynchronously will be logged. Accepting of incoming connections\n        will not be blocked by this coroutine.\n\n        If this `TCPServer` is configured for SSL, ``handle_stream``\n        may be called before the SSL handshake has completed. Use\n        `.SSLIOStream.wait_for_handshake` if you need to verify the client's\n        certificate or use NPN/ALPN.\n\n        .. versionchanged:: 4.2\n           Added the option for this method to be a coroutine.\n        \"\"\"\n        raise NotImplementedError()\n\n    def _handle_connection(self, connection, address):\n        if self.ssl_options is not None:\n            assert ssl, \"Python 2.6+ and OpenSSL required for SSL\"\n            try:\n                connection = ssl_wrap_socket(connection,\n                                             self.ssl_options,\n                                             server_side=True,\n                                             do_handshake_on_connect=False)\n            except ssl.SSLError as err:\n                if err.args[0] == ssl.SSL_ERROR_EOF:\n                    return connection.close()\n                else:\n                    raise\n            except socket.error as err:\n                # If the connection is closed immediately after it is created\n                # (as in a port scan), we can get one of several errors.\n                # wrap_socket makes an internal call to getpeername,\n                # which may return either EINVAL (Mac OS X) or ENOTCONN\n                # (Linux).  If it returns ENOTCONN, this error is\n                # silently swallowed by the ssl module, so we need to\n                # catch another error later on (AttributeError in\n                # SSLIOStream._do_ssl_handshake).\n                # To test this behavior, try nmap with the -sT flag.\n                # https://github.com/tornadoweb/tornado/pull/750\n                if errno_from_exception(err) in (errno.ECONNABORTED, errno.EINVAL):\n                    return connection.close()\n                else:\n                    raise\n        try:\n            if self.ssl_options is not None:\n                stream = SSLIOStream(connection, io_loop=self.io_loop,\n                                     max_buffer_size=self.max_buffer_size,\n                                     read_chunk_size=self.read_chunk_size)\n            else:\n                stream = IOStream(connection, io_loop=self.io_loop,\n                                  max_buffer_size=self.max_buffer_size,\n                                  read_chunk_size=self.read_chunk_size)\n\n            future = self.handle_stream(stream, address)\n            if future is not None:\n                self.io_loop.add_future(gen.convert_yielded(future),\n                                        lambda f: f.result())\n        except Exception:\n            app_log.error(\"Error in connection callback\", exc_info=True)\n",
            "header": {
                "file": {
                    "path": "tornado/tcpserver.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "31f49359",
                "new_commit_hash": "ac666698",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/tornado/tcpserver.py"
            },
            "plus_file": {
                "path": "b/tornado/tcpserver.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 21,
                            "length": 6
                        },
                        "new_range": {
                            "start": 21,
                            "length": 7
                        },
                        "section": "import errno"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "import os",
                                "type": "context"
                            },
                            {
                                "content": "import socket",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "from tornado import gen",
                                "type": "added"
                            },
                            {
                                "content": "from tornado.log import app_log",
                                "type": "context"
                            },
                            {
                                "content": "from tornado.ioloop import IOLoop",
                                "type": "context"
                            },
                            {
                                "content": "from tornado.iostream import IOStream, SSLIOStream",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [
                        {
                            "file_name": "tornado/tcpserver.py",
                            "type": "statement",
                            "name": "",
                            "content": "from tornado import gen",
                            "ast_type_str": "ImportFrom",
                            "start_lineno": 24,
                            "end_lineno": 24,
                            "parent": null
                        }
                    ],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 290,
                            "length": 8
                        },
                        "new_range": {
                            "start": 291,
                            "length": 10
                        },
                        "section": "class TCPServer(object):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "                stream = IOStream(connection, io_loop=self.io_loop,",
                                "type": "context"
                            },
                            {
                                "content": "                                  max_buffer_size=self.max_buffer_size,",
                                "type": "context"
                            },
                            {
                                "content": "                                  read_chunk_size=self.read_chunk_size)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "            future = self.handle_stream(stream, address)",
                                "type": "context"
                            },
                            {
                                "content": "            if future is not None:",
                                "type": "context"
                            },
                            {
                                "content": "                self.io_loop.add_future(future, lambda f: f.result())",
                                "type": "deleted"
                            },
                            {
                                "content": "                self.io_loop.add_future(gen.convert_yielded(future),",
                                "type": "added"
                            },
                            {
                                "content": "                                        lambda f: f.result())",
                                "type": "added"
                            },
                            {
                                "content": "        except Exception:",
                                "type": "context"
                            },
                            {
                                "content": "            app_log.error(\"Error in connection callback\", exc_info=True)",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/tcpserver.py",
                            "type": "method",
                            "name": "TCPServer._handle_connection",
                            "content": "class TCPServer(object):\n    r\"\"\"A non-blocking, single-threaded TCP server.\n\n    To use `TCPServer`, define a subclass which overrides the `handle_stream`\n    method. For example, a simple echo server could be defined like this::\n\n      from tornado.tcpserver import TCPServer\n      from tornado.iostream import StreamClosedError\n      from tornado import gen\n\n      class EchoServer(TCPServer):\n          @gen.coroutine\n          def handle_stream(self, stream, address):\n              while True:\n                  try:\n                      data = yield stream.read_until(b\"\\n\")\n                      yield stream.write(data)\n                  except StreamClosedError:\n                      break\n\n    To make this server serve SSL traffic, send the ``ssl_options`` keyword\n    argument with an `ssl.SSLContext` object. For compatibility with older\n    versions of Python ``ssl_options`` may also be a dictionary of keyword\n    arguments for the `ssl.wrap_socket` method.::\n\n       ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)\n       ssl_ctx.load_cert_chain(os.path.join(data_dir, \"mydomain.crt\"),\n                               os.path.join(data_dir, \"mydomain.key\"))\n       TCPServer(ssl_options=ssl_ctx)\n\n    `TCPServer` initialization follows one of three patterns:\n\n    1. `listen`: simple single-process::\n\n            server = TCPServer()\n            server.listen(8888)\n            IOLoop.current().start()\n\n    2. `bind`/`start`: simple multi-process::\n\n            server = TCPServer()\n            server.bind(8888)\n            server.start(0)  # Forks multiple sub-processes\n            IOLoop.current().start()\n\n       When using this interface, an `.IOLoop` must *not* be passed\n       to the `TCPServer` constructor.  `start` will always start\n       the server on the default singleton `.IOLoop`.\n\n    3. `add_sockets`: advanced multi-process::\n\n            sockets = bind_sockets(8888)\n            tornado.process.fork_processes(0)\n            server = TCPServer()\n            server.add_sockets(sockets)\n            IOLoop.current().start()\n\n       The `add_sockets` interface is more complicated, but it can be\n       used with `tornado.process.fork_processes` to give you more\n       flexibility in when the fork happens.  `add_sockets` can\n       also be used in single-process servers if you want to create\n       your listening sockets in some way other than\n       `~tornado.netutil.bind_sockets`.\n\n    .. versionadded:: 3.1\n       The ``max_buffer_size`` argument.\n    \"\"\"\n    def __init__(self, io_loop=None, ssl_options=None, max_buffer_size=None,\n                 read_chunk_size=None):\n        self.io_loop = io_loop\n        self.ssl_options = ssl_options\n        self._sockets = {}  # fd -> socket object\n        self._pending_sockets = []\n        self._started = False\n        self._stopped = False\n        self.max_buffer_size = max_buffer_size\n        self.read_chunk_size = read_chunk_size\n\n        # Verify the SSL options. Otherwise we don't get errors until clients\n        # connect. This doesn't verify that the keys are legitimate, but\n        # the SSL module doesn't do that until there is a connected socket\n        # which seems like too much work\n        if self.ssl_options is not None and isinstance(self.ssl_options, dict):\n            # Only certfile is required: it can contain both keys\n            if 'certfile' not in self.ssl_options:\n                raise KeyError('missing key \"certfile\" in ssl_options')\n\n            if not os.path.exists(self.ssl_options['certfile']):\n                raise ValueError('certfile \"%s\" does not exist' %\n                                 self.ssl_options['certfile'])\n            if ('keyfile' in self.ssl_options and\n                    not os.path.exists(self.ssl_options['keyfile'])):\n                raise ValueError('keyfile \"%s\" does not exist' %\n                                 self.ssl_options['keyfile'])\n\n    def listen(self, port, address=\"\"):\n        \"\"\"Starts accepting connections on the given port.\n\n        This method may be called more than once to listen on multiple ports.\n        `listen` takes effect immediately; it is not necessary to call\n        `TCPServer.start` afterwards.  It is, however, necessary to start\n        the `.IOLoop`.\n        \"\"\"\n        sockets = bind_sockets(port, address=address)\n        self.add_sockets(sockets)\n\n    def add_sockets(self, sockets):\n        \"\"\"Makes this server start accepting connections on the given sockets.\n\n        The ``sockets`` parameter is a list of socket objects such as\n        those returned by `~tornado.netutil.bind_sockets`.\n        `add_sockets` is typically used in combination with that\n        method and `tornado.process.fork_processes` to provide greater\n        control over the initialization of a multi-process server.\n        \"\"\"\n        if self.io_loop is None:\n            self.io_loop = IOLoop.current()\n\n        for sock in sockets:\n            self._sockets[sock.fileno()] = sock\n            add_accept_handler(sock, self._handle_connection,\n                               io_loop=self.io_loop)\n\n    def add_socket(self, socket):\n        \"\"\"Singular version of `add_sockets`.  Takes a single socket object.\"\"\"\n        self.add_sockets([socket])\n\n    def bind(self, port, address=None, family=socket.AF_UNSPEC, backlog=128,\n             reuse_port=False):\n        \"\"\"Binds this server to the given port on the given address.\n\n        To start the server, call `start`. If you want to run this server\n        in a single process, you can call `listen` as a shortcut to the\n        sequence of `bind` and `start` calls.\n\n        Address may be either an IP address or hostname.  If it's a hostname,\n        the server will listen on all IP addresses associated with the\n        name.  Address may be an empty string or None to listen on all\n        available interfaces.  Family may be set to either `socket.AF_INET`\n        or `socket.AF_INET6` to restrict to IPv4 or IPv6 addresses, otherwise\n        both will be used if available.\n\n        The ``backlog`` argument has the same meaning as for\n        `socket.listen <socket.socket.listen>`. The ``reuse_port`` argument\n        has the same meaning as for `.bind_sockets`.\n\n        This method may be called multiple times prior to `start` to listen\n        on multiple ports or interfaces.\n\n        .. versionchanged:: 4.4\n           Added the ``reuse_port`` argument.\n        \"\"\"\n        sockets = bind_sockets(port, address=address, family=family,\n                               backlog=backlog, reuse_port=reuse_port)\n        if self._started:\n            self.add_sockets(sockets)\n        else:\n            self._pending_sockets.extend(sockets)\n\n    def start(self, num_processes=1):\n        \"\"\"Starts this server in the `.IOLoop`.\n\n        By default, we run the server in this process and do not fork any\n        additional child process.\n\n        If num_processes is ``None`` or <= 0, we detect the number of cores\n        available on this machine and fork that number of child\n        processes. If num_processes is given and > 1, we fork that\n        specific number of sub-processes.\n\n        Since we use processes and not threads, there is no shared memory\n        between any server code.\n\n        Note that multiple processes are not compatible with the autoreload\n        module (or the ``autoreload=True`` option to `tornado.web.Application`\n        which defaults to True when ``debug=True``).\n        When using multiple processes, no IOLoops can be created or\n        referenced until after the call to ``TCPServer.start(n)``.\n        \"\"\"\n        assert not self._started\n        self._started = True\n        if num_processes != 1:\n            process.fork_processes(num_processes)\n        sockets = self._pending_sockets\n        self._pending_sockets = []\n        self.add_sockets(sockets)\n\n    def stop(self):\n        \"\"\"Stops listening for new connections.\n\n        Requests currently in progress may still continue after the\n        server is stopped.\n        \"\"\"\n        if self._stopped:\n            return\n        self._stopped = True\n        for fd, sock in self._sockets.items():\n            assert sock.fileno() == fd\n            self.io_loop.remove_handler(fd)\n            sock.close()\n\n    def handle_stream(self, stream, address):\n        \"\"\"Override to handle a new `.IOStream` from an incoming connection.\n\n        This method may be a coroutine; if so any exceptions it raises\n        asynchronously will be logged. Accepting of incoming connections\n        will not be blocked by this coroutine.\n\n        If this `TCPServer` is configured for SSL, ``handle_stream``\n        may be called before the SSL handshake has completed. Use\n        `.SSLIOStream.wait_for_handshake` if you need to verify the client's\n        certificate or use NPN/ALPN.\n\n        .. versionchanged:: 4.2\n           Added the option for this method to be a coroutine.\n        \"\"\"\n        raise NotImplementedError()\n\n    def _handle_connection(self, connection, address):\n        if self.ssl_options is not None:\n            assert ssl, \"Python 2.6+ and OpenSSL required for SSL\"\n            try:\n                connection = ssl_wrap_socket(connection,\n                                             self.ssl_options,\n                                             server_side=True,\n                                             do_handshake_on_connect=False)\n            except ssl.SSLError as err:\n                if err.args[0] == ssl.SSL_ERROR_EOF:\n                    return connection.close()\n                else:\n                    raise\n            except socket.error as err:\n                # If the connection is closed immediately after it is created\n                # (as in a port scan), we can get one of several errors.\n                # wrap_socket makes an internal call to getpeername,\n                # which may return either EINVAL (Mac OS X) or ENOTCONN\n                # (Linux).  If it returns ENOTCONN, this error is\n                # silently swallowed by the ssl module, so we need to\n                # catch another error later on (AttributeError in\n                # SSLIOStream._do_ssl_handshake).\n                # To test this behavior, try nmap with the -sT flag.\n                # https://github.com/tornadoweb/tornado/pull/750\n                if errno_from_exception(err) in (errno.ECONNABORTED, errno.EINVAL):\n                    return connection.close()\n                else:\n                    raise\n        try:\n            if self.ssl_options is not None:\n                stream = SSLIOStream(connection, io_loop=self.io_loop,\n                                     max_buffer_size=self.max_buffer_size,\n                                     read_chunk_size=self.read_chunk_size)\n            else:\n                stream = IOStream(connection, io_loop=self.io_loop,\n                                  max_buffer_size=self.max_buffer_size,\n                                  read_chunk_size=self.read_chunk_size)\n            future = self.handle_stream(stream, address)\n            if future is not None:\n                self.io_loop.add_future(future, lambda f: f.result())\n        except Exception:\n            app_log.error(\"Error in connection callback\", exc_info=True)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 256,
                            "end_lineno": 297,
                            "parent": {
                                "file_name": "tornado/tcpserver.py",
                                "type": "class",
                                "name": "TCPServer",
                                "content": "class TCPServer(object):\n    r\"\"\"A non-blocking, single-threaded TCP server.\n\n    To use `TCPServer`, define a subclass which overrides the `handle_stream`\n    method. For example, a simple echo server could be defined like this::\n\n      from tornado.tcpserver import TCPServer\n      from tornado.iostream import StreamClosedError\n      from tornado import gen\n\n      class EchoServer(TCPServer):\n          @gen.coroutine\n          def handle_stream(self, stream, address):\n              while True:\n                  try:\n                      data = yield stream.read_until(b\"\\n\")\n                      yield stream.write(data)\n                  except StreamClosedError:\n                      break\n\n    To make this server serve SSL traffic, send the ``ssl_options`` keyword\n    argument with an `ssl.SSLContext` object. For compatibility with older\n    versions of Python ``ssl_options`` may also be a dictionary of keyword\n    arguments for the `ssl.wrap_socket` method.::\n\n       ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)\n       ssl_ctx.load_cert_chain(os.path.join(data_dir, \"mydomain.crt\"),\n                               os.path.join(data_dir, \"mydomain.key\"))\n       TCPServer(ssl_options=ssl_ctx)\n\n    `TCPServer` initialization follows one of three patterns:\n\n    1. `listen`: simple single-process::\n\n            server = TCPServer()\n            server.listen(8888)\n            IOLoop.current().start()\n\n    2. `bind`/`start`: simple multi-process::\n\n            server = TCPServer()\n            server.bind(8888)\n            server.start(0)  # Forks multiple sub-processes\n            IOLoop.current().start()\n\n       When using this interface, an `.IOLoop` must *not* be passed\n       to the `TCPServer` constructor.  `start` will always start\n       the server on the default singleton `.IOLoop`.\n\n    3. `add_sockets`: advanced multi-process::\n\n            sockets = bind_sockets(8888)\n            tornado.process.fork_processes(0)\n            server = TCPServer()\n            server.add_sockets(sockets)\n            IOLoop.current().start()\n\n       The `add_sockets` interface is more complicated, but it can be\n       used with `tornado.process.fork_processes` to give you more\n       flexibility in when the fork happens.  `add_sockets` can\n       also be used in single-process servers if you want to create\n       your listening sockets in some way other than\n       `~tornado.netutil.bind_sockets`.\n\n    .. versionadded:: 3.1\n       The ``max_buffer_size`` argument.\n    \"\"\"\n    def __init__(self, io_loop=None, ssl_options=None, max_buffer_size=None,\n                 read_chunk_size=None):\n        self.io_loop = io_loop\n        self.ssl_options = ssl_options\n        self._sockets = {}  # fd -> socket object\n        self._pending_sockets = []\n        self._started = False\n        self._stopped = False\n        self.max_buffer_size = max_buffer_size\n        self.read_chunk_size = read_chunk_size\n\n        # Verify the SSL options. Otherwise we don't get errors until clients\n        # connect. This doesn't verify that the keys are legitimate, but\n        # the SSL module doesn't do that until there is a connected socket\n        # which seems like too much work\n        if self.ssl_options is not None and isinstance(self.ssl_options, dict):\n            # Only certfile is required: it can contain both keys\n            if 'certfile' not in self.ssl_options:\n                raise KeyError('missing key \"certfile\" in ssl_options')\n\n            if not os.path.exists(self.ssl_options['certfile']):\n                raise ValueError('certfile \"%s\" does not exist' %\n                                 self.ssl_options['certfile'])\n            if ('keyfile' in self.ssl_options and\n                    not os.path.exists(self.ssl_options['keyfile'])):\n                raise ValueError('keyfile \"%s\" does not exist' %\n                                 self.ssl_options['keyfile'])\n\n    def listen(self, port, address=\"\"):\n        \"\"\"Starts accepting connections on the given port.\n\n        This method may be called more than once to listen on multiple ports.\n        `listen` takes effect immediately; it is not necessary to call\n        `TCPServer.start` afterwards.  It is, however, necessary to start\n        the `.IOLoop`.\n        \"\"\"\n        sockets = bind_sockets(port, address=address)\n        self.add_sockets(sockets)\n\n    def add_sockets(self, sockets):\n        \"\"\"Makes this server start accepting connections on the given sockets.\n\n        The ``sockets`` parameter is a list of socket objects such as\n        those returned by `~tornado.netutil.bind_sockets`.\n        `add_sockets` is typically used in combination with that\n        method and `tornado.process.fork_processes` to provide greater\n        control over the initialization of a multi-process server.\n        \"\"\"\n        if self.io_loop is None:\n            self.io_loop = IOLoop.current()\n\n        for sock in sockets:\n            self._sockets[sock.fileno()] = sock\n            add_accept_handler(sock, self._handle_connection,\n                               io_loop=self.io_loop)\n\n    def add_socket(self, socket):\n        \"\"\"Singular version of `add_sockets`.  Takes a single socket object.\"\"\"\n        self.add_sockets([socket])\n\n    def bind(self, port, address=None, family=socket.AF_UNSPEC, backlog=128,\n             reuse_port=False):\n        \"\"\"Binds this server to the given port on the given address.\n\n        To start the server, call `start`. If you want to run this server\n        in a single process, you can call `listen` as a shortcut to the\n        sequence of `bind` and `start` calls.\n\n        Address may be either an IP address or hostname.  If it's a hostname,\n        the server will listen on all IP addresses associated with the\n        name.  Address may be an empty string or None to listen on all\n        available interfaces.  Family may be set to either `socket.AF_INET`\n        or `socket.AF_INET6` to restrict to IPv4 or IPv6 addresses, otherwise\n        both will be used if available.\n\n        The ``backlog`` argument has the same meaning as for\n        `socket.listen <socket.socket.listen>`. The ``reuse_port`` argument\n        has the same meaning as for `.bind_sockets`.\n\n        This method may be called multiple times prior to `start` to listen\n        on multiple ports or interfaces.\n\n        .. versionchanged:: 4.4\n           Added the ``reuse_port`` argument.\n        \"\"\"\n        sockets = bind_sockets(port, address=address, family=family,\n                               backlog=backlog, reuse_port=reuse_port)\n        if self._started:\n            self.add_sockets(sockets)\n        else:\n            self._pending_sockets.extend(sockets)\n\n    def start(self, num_processes=1):\n        \"\"\"Starts this server in the `.IOLoop`.\n\n        By default, we run the server in this process and do not fork any\n        additional child process.\n\n        If num_processes is ``None`` or <= 0, we detect the number of cores\n        available on this machine and fork that number of child\n        processes. If num_processes is given and > 1, we fork that\n        specific number of sub-processes.\n\n        Since we use processes and not threads, there is no shared memory\n        between any server code.\n\n        Note that multiple processes are not compatible with the autoreload\n        module (or the ``autoreload=True`` option to `tornado.web.Application`\n        which defaults to True when ``debug=True``).\n        When using multiple processes, no IOLoops can be created or\n        referenced until after the call to ``TCPServer.start(n)``.\n        \"\"\"\n        assert not self._started\n        self._started = True\n        if num_processes != 1:\n            process.fork_processes(num_processes)\n        sockets = self._pending_sockets\n        self._pending_sockets = []\n        self.add_sockets(sockets)\n\n    def stop(self):\n        \"\"\"Stops listening for new connections.\n\n        Requests currently in progress may still continue after the\n        server is stopped.\n        \"\"\"\n        if self._stopped:\n            return\n        self._stopped = True\n        for fd, sock in self._sockets.items():\n            assert sock.fileno() == fd\n            self.io_loop.remove_handler(fd)\n            sock.close()\n\n    def handle_stream(self, stream, address):\n        \"\"\"Override to handle a new `.IOStream` from an incoming connection.\n\n        This method may be a coroutine; if so any exceptions it raises\n        asynchronously will be logged. Accepting of incoming connections\n        will not be blocked by this coroutine.\n\n        If this `TCPServer` is configured for SSL, ``handle_stream``\n        may be called before the SSL handshake has completed. Use\n        `.SSLIOStream.wait_for_handshake` if you need to verify the client's\n        certificate or use NPN/ALPN.\n\n        .. versionchanged:: 4.2\n           Added the option for this method to be a coroutine.\n        \"\"\"\n        raise NotImplementedError()\n\n    def _handle_connection(self, connection, address):\n        if self.ssl_options is not None:\n            assert ssl, \"Python 2.6+ and OpenSSL required for SSL\"\n            try:\n                connection = ssl_wrap_socket(connection,\n                                             self.ssl_options,\n                                             server_side=True,\n                                             do_handshake_on_connect=False)\n            except ssl.SSLError as err:\n                if err.args[0] == ssl.SSL_ERROR_EOF:\n                    return connection.close()\n                else:\n                    raise\n            except socket.error as err:\n                # If the connection is closed immediately after it is created\n                # (as in a port scan), we can get one of several errors.\n                # wrap_socket makes an internal call to getpeername,\n                # which may return either EINVAL (Mac OS X) or ENOTCONN\n                # (Linux).  If it returns ENOTCONN, this error is\n                # silently swallowed by the ssl module, so we need to\n                # catch another error later on (AttributeError in\n                # SSLIOStream._do_ssl_handshake).\n                # To test this behavior, try nmap with the -sT flag.\n                # https://github.com/tornadoweb/tornado/pull/750\n                if errno_from_exception(err) in (errno.ECONNABORTED, errno.EINVAL):\n                    return connection.close()\n                else:\n                    raise\n        try:\n            if self.ssl_options is not None:\n                stream = SSLIOStream(connection, io_loop=self.io_loop,\n                                     max_buffer_size=self.max_buffer_size,\n                                     read_chunk_size=self.read_chunk_size)\n            else:\n                stream = IOStream(connection, io_loop=self.io_loop,\n                                  max_buffer_size=self.max_buffer_size,\n                                  read_chunk_size=self.read_chunk_size)\n            future = self.handle_stream(stream, address)\n            if future is not None:\n                self.io_loop.add_future(future, lambda f: f.result())\n        except Exception:\n            app_log.error(\"Error in connection callback\", exc_info=True)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 38,
                                "end_lineno": 297,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/tcpserver.py",
                            "type": "class",
                            "name": "TCPServer",
                            "content": "class TCPServer(object):\n    r\"\"\"A non-blocking, single-threaded TCP server.\n\n    To use `TCPServer`, define a subclass which overrides the `handle_stream`\n    method. For example, a simple echo server could be defined like this::\n\n      from tornado.tcpserver import TCPServer\n      from tornado.iostream import StreamClosedError\n      from tornado import gen\n\n      class EchoServer(TCPServer):\n          @gen.coroutine\n          def handle_stream(self, stream, address):\n              while True:\n                  try:\n                      data = yield stream.read_until(b\"\\n\")\n                      yield stream.write(data)\n                  except StreamClosedError:\n                      break\n\n    To make this server serve SSL traffic, send the ``ssl_options`` keyword\n    argument with an `ssl.SSLContext` object. For compatibility with older\n    versions of Python ``ssl_options`` may also be a dictionary of keyword\n    arguments for the `ssl.wrap_socket` method.::\n\n       ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)\n       ssl_ctx.load_cert_chain(os.path.join(data_dir, \"mydomain.crt\"),\n                               os.path.join(data_dir, \"mydomain.key\"))\n       TCPServer(ssl_options=ssl_ctx)\n\n    `TCPServer` initialization follows one of three patterns:\n\n    1. `listen`: simple single-process::\n\n            server = TCPServer()\n            server.listen(8888)\n            IOLoop.current().start()\n\n    2. `bind`/`start`: simple multi-process::\n\n            server = TCPServer()\n            server.bind(8888)\n            server.start(0)  # Forks multiple sub-processes\n            IOLoop.current().start()\n\n       When using this interface, an `.IOLoop` must *not* be passed\n       to the `TCPServer` constructor.  `start` will always start\n       the server on the default singleton `.IOLoop`.\n\n    3. `add_sockets`: advanced multi-process::\n\n            sockets = bind_sockets(8888)\n            tornado.process.fork_processes(0)\n            server = TCPServer()\n            server.add_sockets(sockets)\n            IOLoop.current().start()\n\n       The `add_sockets` interface is more complicated, but it can be\n       used with `tornado.process.fork_processes` to give you more\n       flexibility in when the fork happens.  `add_sockets` can\n       also be used in single-process servers if you want to create\n       your listening sockets in some way other than\n       `~tornado.netutil.bind_sockets`.\n\n    .. versionadded:: 3.1\n       The ``max_buffer_size`` argument.\n    \"\"\"\n    def __init__(self, io_loop=None, ssl_options=None, max_buffer_size=None,\n                 read_chunk_size=None):\n        self.io_loop = io_loop\n        self.ssl_options = ssl_options\n        self._sockets = {}  # fd -> socket object\n        self._pending_sockets = []\n        self._started = False\n        self._stopped = False\n        self.max_buffer_size = max_buffer_size\n        self.read_chunk_size = read_chunk_size\n\n        # Verify the SSL options. Otherwise we don't get errors until clients\n        # connect. This doesn't verify that the keys are legitimate, but\n        # the SSL module doesn't do that until there is a connected socket\n        # which seems like too much work\n        if self.ssl_options is not None and isinstance(self.ssl_options, dict):\n            # Only certfile is required: it can contain both keys\n            if 'certfile' not in self.ssl_options:\n                raise KeyError('missing key \"certfile\" in ssl_options')\n\n            if not os.path.exists(self.ssl_options['certfile']):\n                raise ValueError('certfile \"%s\" does not exist' %\n                                 self.ssl_options['certfile'])\n            if ('keyfile' in self.ssl_options and\n                    not os.path.exists(self.ssl_options['keyfile'])):\n                raise ValueError('keyfile \"%s\" does not exist' %\n                                 self.ssl_options['keyfile'])\n\n    def listen(self, port, address=\"\"):\n        \"\"\"Starts accepting connections on the given port.\n\n        This method may be called more than once to listen on multiple ports.\n        `listen` takes effect immediately; it is not necessary to call\n        `TCPServer.start` afterwards.  It is, however, necessary to start\n        the `.IOLoop`.\n        \"\"\"\n        sockets = bind_sockets(port, address=address)\n        self.add_sockets(sockets)\n\n    def add_sockets(self, sockets):\n        \"\"\"Makes this server start accepting connections on the given sockets.\n\n        The ``sockets`` parameter is a list of socket objects such as\n        those returned by `~tornado.netutil.bind_sockets`.\n        `add_sockets` is typically used in combination with that\n        method and `tornado.process.fork_processes` to provide greater\n        control over the initialization of a multi-process server.\n        \"\"\"\n        if self.io_loop is None:\n            self.io_loop = IOLoop.current()\n\n        for sock in sockets:\n            self._sockets[sock.fileno()] = sock\n            add_accept_handler(sock, self._handle_connection,\n                               io_loop=self.io_loop)\n\n    def add_socket(self, socket):\n        \"\"\"Singular version of `add_sockets`.  Takes a single socket object.\"\"\"\n        self.add_sockets([socket])\n\n    def bind(self, port, address=None, family=socket.AF_UNSPEC, backlog=128,\n             reuse_port=False):\n        \"\"\"Binds this server to the given port on the given address.\n\n        To start the server, call `start`. If you want to run this server\n        in a single process, you can call `listen` as a shortcut to the\n        sequence of `bind` and `start` calls.\n\n        Address may be either an IP address or hostname.  If it's a hostname,\n        the server will listen on all IP addresses associated with the\n        name.  Address may be an empty string or None to listen on all\n        available interfaces.  Family may be set to either `socket.AF_INET`\n        or `socket.AF_INET6` to restrict to IPv4 or IPv6 addresses, otherwise\n        both will be used if available.\n\n        The ``backlog`` argument has the same meaning as for\n        `socket.listen <socket.socket.listen>`. The ``reuse_port`` argument\n        has the same meaning as for `.bind_sockets`.\n\n        This method may be called multiple times prior to `start` to listen\n        on multiple ports or interfaces.\n\n        .. versionchanged:: 4.4\n           Added the ``reuse_port`` argument.\n        \"\"\"\n        sockets = bind_sockets(port, address=address, family=family,\n                               backlog=backlog, reuse_port=reuse_port)\n        if self._started:\n            self.add_sockets(sockets)\n        else:\n            self._pending_sockets.extend(sockets)\n\n    def start(self, num_processes=1):\n        \"\"\"Starts this server in the `.IOLoop`.\n\n        By default, we run the server in this process and do not fork any\n        additional child process.\n\n        If num_processes is ``None`` or <= 0, we detect the number of cores\n        available on this machine and fork that number of child\n        processes. If num_processes is given and > 1, we fork that\n        specific number of sub-processes.\n\n        Since we use processes and not threads, there is no shared memory\n        between any server code.\n\n        Note that multiple processes are not compatible with the autoreload\n        module (or the ``autoreload=True`` option to `tornado.web.Application`\n        which defaults to True when ``debug=True``).\n        When using multiple processes, no IOLoops can be created or\n        referenced until after the call to ``TCPServer.start(n)``.\n        \"\"\"\n        assert not self._started\n        self._started = True\n        if num_processes != 1:\n            process.fork_processes(num_processes)\n        sockets = self._pending_sockets\n        self._pending_sockets = []\n        self.add_sockets(sockets)\n\n    def stop(self):\n        \"\"\"Stops listening for new connections.\n\n        Requests currently in progress may still continue after the\n        server is stopped.\n        \"\"\"\n        if self._stopped:\n            return\n        self._stopped = True\n        for fd, sock in self._sockets.items():\n            assert sock.fileno() == fd\n            self.io_loop.remove_handler(fd)\n            sock.close()\n\n    def handle_stream(self, stream, address):\n        \"\"\"Override to handle a new `.IOStream` from an incoming connection.\n\n        This method may be a coroutine; if so any exceptions it raises\n        asynchronously will be logged. Accepting of incoming connections\n        will not be blocked by this coroutine.\n\n        If this `TCPServer` is configured for SSL, ``handle_stream``\n        may be called before the SSL handshake has completed. Use\n        `.SSLIOStream.wait_for_handshake` if you need to verify the client's\n        certificate or use NPN/ALPN.\n\n        .. versionchanged:: 4.2\n           Added the option for this method to be a coroutine.\n        \"\"\"\n        raise NotImplementedError()\n\n    def _handle_connection(self, connection, address):\n        if self.ssl_options is not None:\n            assert ssl, \"Python 2.6+ and OpenSSL required for SSL\"\n            try:\n                connection = ssl_wrap_socket(connection,\n                                             self.ssl_options,\n                                             server_side=True,\n                                             do_handshake_on_connect=False)\n            except ssl.SSLError as err:\n                if err.args[0] == ssl.SSL_ERROR_EOF:\n                    return connection.close()\n                else:\n                    raise\n            except socket.error as err:\n                # If the connection is closed immediately after it is created\n                # (as in a port scan), we can get one of several errors.\n                # wrap_socket makes an internal call to getpeername,\n                # which may return either EINVAL (Mac OS X) or ENOTCONN\n                # (Linux).  If it returns ENOTCONN, this error is\n                # silently swallowed by the ssl module, so we need to\n                # catch another error later on (AttributeError in\n                # SSLIOStream._do_ssl_handshake).\n                # To test this behavior, try nmap with the -sT flag.\n                # https://github.com/tornadoweb/tornado/pull/750\n                if errno_from_exception(err) in (errno.ECONNABORTED, errno.EINVAL):\n                    return connection.close()\n                else:\n                    raise\n        try:\n            if self.ssl_options is not None:\n                stream = SSLIOStream(connection, io_loop=self.io_loop,\n                                     max_buffer_size=self.max_buffer_size,\n                                     read_chunk_size=self.read_chunk_size)\n            else:\n                stream = IOStream(connection, io_loop=self.io_loop,\n                                  max_buffer_size=self.max_buffer_size,\n                                  read_chunk_size=self.read_chunk_size)\n            future = self.handle_stream(stream, address)\n            if future is not None:\n                self.io_loop.add_future(future, lambda f: f.result())\n        except Exception:\n            app_log.error(\"Error in connection callback\", exc_info=True)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 38,
                            "end_lineno": 297,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "from __future__ import absolute_import, division, print_function, with_statement\n\nimport socket\n\nfrom tornado import gen\nfrom tornado.iostream import IOStream\nfrom tornado.log import app_log\nfrom tornado.stack_context import NullContext\nfrom tornado.tcpserver import TCPServer\nfrom tornado.testing import AsyncTestCase, ExpectLog, bind_unused_port, gen_test\n\n\nclass TCPServerTest(AsyncTestCase):\n    @gen_test\n    def test_handle_stream_coroutine_logging(self):\n        # handle_stream may be a coroutine and any exception in its\n        # Future will be logged.\n        class TestServer(TCPServer):\n            @gen.coroutine\n            def handle_stream(self, stream, address):\n                yield gen.moment\n                stream.close()\n                1 / 0\n\n        server = client = None\n        try:\n            sock, port = bind_unused_port()\n            with NullContext():\n                server = TestServer()\n                server.add_socket(sock)\n            client = IOStream(socket.socket())\n            with ExpectLog(app_log, \"Exception in callback\"):\n                yield client.connect(('localhost', port))\n                yield client.read_until_close()\n                yield gen.moment\n        finally:\n            if server is not None:\n                server.stop()\n            if client is not None:\n                client.close()\n\n    def test_stop_twice(self):\n        sock, port = bind_unused_port()\n        server = TCPServer()\n        server.add_socket(sock)\n        server.stop()\n        server.stop()\n\n",
            "new_file_content": "from __future__ import absolute_import, division, print_function, with_statement\n\nimport socket\n\nfrom tornado import gen\nfrom tornado.iostream import IOStream\nfrom tornado.log import app_log\nfrom tornado.stack_context import NullContext\nfrom tornado.tcpserver import TCPServer\nfrom tornado.test.util import skipBefore35, exec_test\nfrom tornado.testing import AsyncTestCase, ExpectLog, bind_unused_port, gen_test\n\n\nclass TCPServerTest(AsyncTestCase):\n    @gen_test\n    def test_handle_stream_coroutine_logging(self):\n        # handle_stream may be a coroutine and any exception in its\n        # Future will be logged.\n        class TestServer(TCPServer):\n            @gen.coroutine\n            def handle_stream(self, stream, address):\n                yield gen.moment\n                stream.close()\n                1 / 0\n\n        server = client = None\n        try:\n            sock, port = bind_unused_port()\n            with NullContext():\n                server = TestServer()\n                server.add_socket(sock)\n            client = IOStream(socket.socket())\n            with ExpectLog(app_log, \"Exception in callback\"):\n                yield client.connect(('localhost', port))\n                yield client.read_until_close()\n                yield gen.moment\n        finally:\n            if server is not None:\n                server.stop()\n            if client is not None:\n                client.close()\n\n    @skipBefore35\n    @gen_test\n    def test_handle_stream_native_coroutine(self):\n        # handle_stream may be a native coroutine.\n\n        namespace = exec_test(globals(), locals(), \"\"\"\n        class TestServer(TCPServer):\n            async def handle_stream(self, stream, address):\n                stream.write(b'data')\n                stream.close()\n        \"\"\")\n\n        sock, port = bind_unused_port()\n        server = namespace['TestServer']()\n        server.add_socket(sock)\n        client = IOStream(socket.socket())\n        yield client.connect(('localhost', port))\n        result = yield client.read_until_close()\n        self.assertEqual(result, b'data')\n        server.stop()\n        client.close()\n\n    def test_stop_twice(self):\n        sock, port = bind_unused_port()\n        server = TCPServer()\n        server.add_socket(sock)\n        server.stop()\n        server.stop()\n\n",
            "header": {
                "file": {
                    "path": "tornado/test/tcpserver_test.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "5c51c71f",
                "new_commit_hash": "2d20b796",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/tornado/test/tcpserver_test.py"
            },
            "plus_file": {
                "path": "b/tornado/test/tcpserver_test.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 7,
                            "length": 6
                        },
                        "new_range": {
                            "start": 7,
                            "length": 7
                        },
                        "section": "from tornado.iostream import IOStream"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "from tornado.log import app_log",
                                "type": "context"
                            },
                            {
                                "content": "from tornado.stack_context import NullContext",
                                "type": "context"
                            },
                            {
                                "content": "from tornado.tcpserver import TCPServer",
                                "type": "context"
                            },
                            {
                                "content": "from tornado.test.util import skipBefore35, exec_test",
                                "type": "added"
                            },
                            {
                                "content": "from tornado.testing import AsyncTestCase, ExpectLog, bind_unused_port, gen_test",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [
                        {
                            "file_name": "tornado/test/tcpserver_test.py",
                            "type": "statement",
                            "name": "",
                            "content": "from tornado.test.util import skipBefore35, exec_test",
                            "ast_type_str": "ImportFrom",
                            "start_lineno": 10,
                            "end_lineno": 10,
                            "parent": null
                        }
                    ],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 39,
                            "length": 6
                        },
                        "new_range": {
                            "start": 40,
                            "length": 28
                        },
                        "section": "class TCPServerTest(AsyncTestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "            if client is not None:",
                                "type": "context"
                            },
                            {
                                "content": "                client.close()",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    @skipBefore35",
                                "type": "added"
                            },
                            {
                                "content": "    @gen_test",
                                "type": "added"
                            },
                            {
                                "content": "    def test_handle_stream_native_coroutine(self):",
                                "type": "added"
                            },
                            {
                                "content": "        # handle_stream may be a native coroutine.",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        namespace = exec_test(globals(), locals(), \"\"\"",
                                "type": "added"
                            },
                            {
                                "content": "        class TestServer(TCPServer):",
                                "type": "added"
                            },
                            {
                                "content": "            async def handle_stream(self, stream, address):",
                                "type": "added"
                            },
                            {
                                "content": "                stream.write(b'data')",
                                "type": "added"
                            },
                            {
                                "content": "                stream.close()",
                                "type": "added"
                            },
                            {
                                "content": "        \"\"\")",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        sock, port = bind_unused_port()",
                                "type": "added"
                            },
                            {
                                "content": "        server = namespace['TestServer']()",
                                "type": "added"
                            },
                            {
                                "content": "        server.add_socket(sock)",
                                "type": "added"
                            },
                            {
                                "content": "        client = IOStream(socket.socket())",
                                "type": "added"
                            },
                            {
                                "content": "        yield client.connect(('localhost', port))",
                                "type": "added"
                            },
                            {
                                "content": "        result = yield client.read_until_close()",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertEqual(result, b'data')",
                                "type": "added"
                            },
                            {
                                "content": "        server.stop()",
                                "type": "added"
                            },
                            {
                                "content": "        client.close()",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    def test_stop_twice(self):",
                                "type": "context"
                            },
                            {
                                "content": "        sock, port = bind_unused_port()",
                                "type": "context"
                            },
                            {
                                "content": "        server = TCPServer()",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/test/tcpserver_test.py",
                            "type": "class",
                            "name": "TCPServerTest",
                            "content": "class TCPServerTest(AsyncTestCase):\n    @gen_test\n    def test_handle_stream_coroutine_logging(self):\n        # handle_stream may be a coroutine and any exception in its\n        # Future will be logged.\n        class TestServer(TCPServer):\n            @gen.coroutine\n            def handle_stream(self, stream, address):\n                yield gen.moment\n                stream.close()\n                1 / 0\n\n        server = client = None\n        try:\n            sock, port = bind_unused_port()\n            with NullContext():\n                server = TestServer()\n                server.add_socket(sock)\n            client = IOStream(socket.socket())\n            with ExpectLog(app_log, \"Exception in callback\"):\n                yield client.connect(('localhost', port))\n                yield client.read_until_close()\n                yield gen.moment\n        finally:\n            if server is not None:\n                server.stop()\n            if client is not None:\n                client.close()\n\n    @skipBefore35\n    @gen_test\n    def test_handle_stream_native_coroutine(self):\n        # handle_stream may be a native coroutine.\n\n        namespace = exec_test(globals(), locals(), \"\"\"\n        class TestServer(TCPServer):\n            async def handle_stream(self, stream, address):\n                stream.write(b'data')\n                stream.close()\n        \"\"\")\n\n        sock, port = bind_unused_port()\n        server = namespace['TestServer']()\n        server.add_socket(sock)\n        client = IOStream(socket.socket())\n        yield client.connect(('localhost', port))\n        result = yield client.read_until_close()\n        self.assertEqual(result, b'data')\n        server.stop()\n        client.close()\n\n    def test_stop_twice(self):\n        sock, port = bind_unused_port()\n        server = TCPServer()\n        server.add_socket(sock)\n        server.stop()\n        server.stop()",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 14,
                            "end_lineno": 70,
                            "parent": null
                        }
                    ],
                    "added_entities": [
                        {
                            "file_name": "tornado/test/tcpserver_test.py",
                            "type": "method",
                            "name": "TCPServerTest.test_handle_stream_native_coroutine",
                            "content": "class TCPServerTest(AsyncTestCase):\n    @gen_test\n    def test_handle_stream_coroutine_logging(self):\n        # handle_stream may be a coroutine and any exception in its\n        # Future will be logged.\n        class TestServer(TCPServer):\n            @gen.coroutine\n            def handle_stream(self, stream, address):\n                yield gen.moment\n                stream.close()\n                1 / 0\n\n        server = client = None\n        try:\n            sock, port = bind_unused_port()\n            with NullContext():\n                server = TestServer()\n                server.add_socket(sock)\n            client = IOStream(socket.socket())\n            with ExpectLog(app_log, \"Exception in callback\"):\n                yield client.connect(('localhost', port))\n                yield client.read_until_close()\n                yield gen.moment\n        finally:\n            if server is not None:\n                server.stop()\n            if client is not None:\n                client.close()\n\n    @skipBefore35\n    @gen_test\n    def test_handle_stream_native_coroutine(self):\n        # handle_stream may be a native coroutine.\n\n        namespace = exec_test(globals(), locals(), \"\"\"\n        class TestServer(TCPServer):\n            async def handle_stream(self, stream, address):\n                stream.write(b'data')\n                stream.close()\n        \"\"\")\n\n        sock, port = bind_unused_port()\n        server = namespace['TestServer']()\n        server.add_socket(sock)\n        client = IOStream(socket.socket())\n        yield client.connect(('localhost', port))\n        result = yield client.read_until_close()\n        self.assertEqual(result, b'data')\n        server.stop()\n        client.close()\n\n    def test_stop_twice(self):\n        sock, port = bind_unused_port()\n        server = TCPServer()\n        server.add_socket(sock)\n        server.stop()\n        server.stop()",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 45,
                            "end_lineno": 63,
                            "parent": {
                                "file_name": "tornado/test/tcpserver_test.py",
                                "type": "class",
                                "name": "TCPServerTest",
                                "content": "class TCPServerTest(AsyncTestCase):\n    @gen_test\n    def test_handle_stream_coroutine_logging(self):\n        # handle_stream may be a coroutine and any exception in its\n        # Future will be logged.\n        class TestServer(TCPServer):\n            @gen.coroutine\n            def handle_stream(self, stream, address):\n                yield gen.moment\n                stream.close()\n                1 / 0\n\n        server = client = None\n        try:\n            sock, port = bind_unused_port()\n            with NullContext():\n                server = TestServer()\n                server.add_socket(sock)\n            client = IOStream(socket.socket())\n            with ExpectLog(app_log, \"Exception in callback\"):\n                yield client.connect(('localhost', port))\n                yield client.read_until_close()\n                yield gen.moment\n        finally:\n            if server is not None:\n                server.stop()\n            if client is not None:\n                client.close()\n\n    @skipBefore35\n    @gen_test\n    def test_handle_stream_native_coroutine(self):\n        # handle_stream may be a native coroutine.\n\n        namespace = exec_test(globals(), locals(), \"\"\"\n        class TestServer(TCPServer):\n            async def handle_stream(self, stream, address):\n                stream.write(b'data')\n                stream.close()\n        \"\"\")\n\n        sock, port = bind_unused_port()\n        server = namespace['TestServer']()\n        server.add_socket(sock)\n        client = IOStream(socket.socket())\n        yield client.connect(('localhost', port))\n        result = yield client.read_until_close()\n        self.assertEqual(result, b'data')\n        server.stop()\n        client.close()\n\n    def test_stop_twice(self):\n        sock, port = bind_unused_port()\n        server = TCPServer()\n        server.add_socket(sock)\n        server.stop()\n        server.stop()",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 14,
                                "end_lineno": 70,
                                "parent": null
                            }
                        }
                    ],
                    "deleted_entities": []
                }
            ]
        }
    ],
    "old_commit_hash": "cadb2e4f7fc6227113d78ae4e9361f72de66622a^",
    "new_commit_hash": "cadb2e4f7fc6227113d78ae4e9361f72de66622a",
    "commit_message": "Merge pull request #1906 from ajdavis/handle-stream-native-coro\n\ntcpserver: handle_stream can be a native coroutine",
    "commit_date": "2016-12-13T21:46:01+08:00",
    "metadata": {}
}
{
    "repo_name": "tornado",
    "new_commit_hash": "cadb2e4f7fc6227113d78ae4e9361f72de66622a",
    "test_file_codes": [
        "from __future__ import absolute_import, division, print_function, with_statement\n\nimport socket\n\nfrom tornado import gen\nfrom tornado.iostream import IOStream\nfrom tornado.log import app_log\nfrom tornado.stack_context import NullContext\nfrom tornado.tcpserver import TCPServer\nfrom tornado.test.util import skipBefore35, exec_test\nfrom tornado.testing import AsyncTestCase, ExpectLog, bind_unused_port, gen_test\n\n\nclass TCPServerTest(AsyncTestCase):\n    @gen_test\n    def test_handle_stream_coroutine_logging(self):\n        # handle_stream may be a coroutine and any exception in its\n        # Future will be logged.\n        class TestServer(TCPServer):\n            @gen.coroutine\n            def handle_stream(self, stream, address):\n                yield gen.moment\n                stream.close()\n                1 / 0\n\n        server = client = None\n        try:\n            sock, port = bind_unused_port()\n            with NullContext():\n                server = TestServer()\n                server.add_socket(sock)\n            client = IOStream(socket.socket())\n            with ExpectLog(app_log, \"Exception in callback\"):\n                yield client.connect(('localhost', port))\n                yield client.read_until_close()\n                yield gen.moment\n        finally:\n            if server is not None:\n                server.stop()\n            if client is not None:\n                client.close()\n\n    @skipBefore35\n    @gen_test\n    def test_handle_stream_native_coroutine(self):\n        # handle_stream may be a native coroutine.\n\n        namespace = exec_test(globals(), locals(), \"\"\"\n        class TestServer(TCPServer):\n            async def handle_stream(self, stream, address):\n                stream.write(b'data')\n                stream.close()\n        \"\"\")\n\n        sock, port = bind_unused_port()\n        server = namespace['TestServer']()\n        server.add_socket(sock)\n        client = IOStream(socket.socket())\n        yield client.connect(('localhost', port))\n        result = yield client.read_until_close()\n        self.assertEqual(result, b'data')\n        server.stop()\n        client.close()\n\n    def test_stop_twice(self):\n        sock, port = bind_unused_port()\n        server = TCPServer()\n        server.add_socket(sock)\n        server.stop()\n        server.stop()\n\n",
        "#!/usr/bin/env python\nimport unittest\nimport sys\nimport time\nimport traceback\nimport platform\nimport os\n\n\nclass PytestLikeResult(unittest.TestResult):\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n        self.start_time = None\n        # Store (test, outcome, info) for each test:\n        #   outcome ∈ { \"passed\", \"failed\", \"error\", \"skipped\" }\n        #   info can hold the exception or skip reason, etc.\n        self.results = []\n\n    def startTestRun(self):\n        \"\"\"Called once before all tests.\"\"\"\n        self.start_time = time.time()\n        # Print a header similar to pytest\n        print(\"=\" * 29 + \" test session starts \" + \"=\" * 29)\n        # You can customize the platform/versions/paths as you like:\n        print(\n            f\"platform {platform.system().lower()} -- Python {platform.python_version()}\"\n        )\n        print(f\"rootdir: {os.path.abspath(os.curdir)}\")\n\n    def stopTestRun(self):\n        \"\"\"Called once after all tests are done.\"\"\"\n        elapsed = time.time() - self.start_time\n        print()  # blank line after final dot\n\n        # Summarize\n        ntests = len(self.results)\n        print(f\"collected {ntests} items\")\n\n        # Show details of failures/errors\n        failures = [r for r in self.results if r[1] == \"failed\"]\n        errors = [r for r in self.results if r[1] == \"error\"]\n\n        if failures:\n            print(\"\\n\" + \"=\" * 35 + \" FAILURES \" + \"=\" * 35)\n            for test, outcome, err_info in failures:\n                test = test.split(\"::\")\n                if len(test) == 3:\n                    test = f\"{test[1]}.{test[2]}\"\n                else:\n                    test = f\"{test[1]}\"\n                print(f\"__________ {test} __________\")\n                self._print_traceback(err_info)\n        if errors:\n            print(\"\\n\" + \"=\" * 35 + \" ERRORS \" + \"=\" * 37)\n            for test, outcome, err_info in errors:\n                test = test.split(\"::\")\n                if len(test) == 3:\n                    test = f\"{test[1]}.{test[2]}\"\n                else:\n                    test = f\"{test[1]}\"\n                print(f\"__________ {test} __________\")\n                self._print_traceback(err_info)\n\n        # Optional short summary lines for passes/fails/skips\n        print(\"\\n==================== short test summary info ====================\")\n        for test, outcome, info in self.results:\n            if outcome in (\"passed\", \"failed\", \"error\", \"skipped\"):\n                print(f\"{outcome.upper()} {test}\")\n\n        # Final one-line summary: “1 failed, 1 errors, 10 passed in 2.04s”\n        passed_count = sum(1 for r in self.results if r[1] == \"passed\")\n        failed_count = len(failures)\n        error_count = len(errors)\n        skipped_count = sum(1 for r in self.results if r[1] == \"skipped\")\n\n        summary_bits = []\n        if failed_count:\n            summary_bits.append(f\"{failed_count} failed\")\n        if error_count:\n            summary_bits.append(f\"{error_count} error{'s' if error_count != 1 else ''}\")\n        if passed_count:\n            summary_bits.append(f\"{passed_count} passed\")\n        if skipped_count:\n            summary_bits.append(f\"{skipped_count} skipped\")\n\n        summary_str = \", \".join(summary_bits) if summary_bits else \"no tests run\"\n        print(\n            f\"=================== {summary_str} in {elapsed:.2f}s ===================\"\n        )\n\n    def startTest(self, test):\n        \"\"\"Called right before each test method.\"\"\"\n        super().startTest(test)\n        # Print a dot or some indicator\n        print(\".\", end=\"\", flush=True)\n\n    def addSuccess(self, test):\n        super().addSuccess(test)\n        self.results.append((self._test_id(test), \"passed\", None))\n\n    def addFailure(self, test, err):\n        super().addFailure(test, err)\n        self.results.append((self._test_id(test), \"failed\", err))\n\n    def addError(self, test, err):\n        super().addError(test, err)\n        self.results.append((self._test_id(test), \"error\", err))\n\n    def addSkip(self, test, reason):\n        super().addSkip(test, reason)\n        self.results.append((self._test_id(test), \"skipped\", reason))\n\n    def _print_traceback(self, err_info):\n        \"\"\"Helper to print the traceback like pytest does.\"\"\"\n        if isinstance(err_info, tuple) and len(err_info) == 3:\n            exc_type, exc_value, tb = err_info\n            traceback.print_exception(exc_type, exc_value, tb, file=sys.stdout)\n        else:\n            print(str(err_info))\n\n    def _test_id(self, test):\n        try:\n            return f\"{test.__class__.__module__}::{test.__class__.__name__}::{test._testMethodName}\"\n        except AttributeError:\n            # Fallback for _ErrorHolder objects\n            return f\"{test.__class__.__module__}::{test.__class__.__name__}\"\n\n\nclass PytestLikeRunner(unittest.TextTestRunner):\n    \"\"\"A custom TextTestRunner that uses the PytestLikeResult.\"\"\"\n\n    resultclass = PytestLikeResult\n\n    def run(self, test):\n        result = self._makeResult()\n        # Overriding run to ensure we call startTestRun/stopTestRun\n        result.startTestRun()\n        test(result)\n        result.stopTestRun()\n        return result\n\n    def tearDown(self):\n        # Reset signal handlers\n        from twisted.internet import reactor\n\n        reactor.removeAll()\n        reactor.stop()\n        super().tearDown()\n\n\ndef main():\n    loader = unittest.TestLoader()\n    suite = loader.discover(\".\", pattern=\"test_*.py\")  # discover tests in r2e_tests/\n    runner = PytestLikeRunner(verbosity=0)\n    result = runner.run(suite)\n    # Exit with code 0 if all tests passed/skipped, 1 if there were fails/errors\n    sys.exit(not result.wasSuccessful())\n\n\nif __name__ == \"__main__\":\n    main()\n"
    ],
    "test_file_names": [
        "test_1.py",
        "tornado_unittest_runner.py"
    ],
    "setup_res_code": 0,
    "setup_res_stdout": "",
    "setup_res_stderr": "Using CPython 3.9.21\nCreating virtual environment at: .venv\nActivate with: source .venv/bin/activate\nResolved 1 package in 756ms\nPrepared 1 package in 1.19s\nInstalled 1 package in 1ms\n + tornado==4.5.dev1 (from file:///home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_cadb2e4f7fc6227113d78ae4e9361f72de66622a)\nResolved 29 packages in 18ms\nInstalled 29 packages in 87ms\n + attrs==24.3.0\n + automat==24.8.1\n + cachetools==5.5.0\n + cffi==1.17.1\n + chardet==5.2.0\n + colorama==0.4.6\n + constantly==23.10.4\n + distlib==0.3.9\n + exceptiongroup==1.2.2\n + filelock==3.16.1\n + hyperlink==21.0.0\n + idna==3.10\n + incremental==24.7.2\n + iniconfig==2.0.0\n + packaging==24.2\n + platformdirs==4.3.6\n + pluggy==1.5.0\n + pycares==4.5.0\n + pycparser==2.22\n + pycurl==7.45.4\n + pyproject-api==1.8.0\n + pytest==8.3.4\n + setuptools==75.6.0\n + tomli==2.2.1\n + tox==4.23.2\n + twisted==24.11.0\n + typing-extensions==4.12.2\n + virtualenv==20.28.0\n + zope-interface==7.2\n",
    "new_commit_res_code": 0,
    "new_commit_res_stdout": "============================= test session starts =============================\nplatform linux -- Python 3.9.21\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_cadb2e4f7fc6227113d78ae4e9361f72de66622a\n...\ncollected 3 items\n\n==================== short test summary info ====================\nPASSED r2e_tests.test_1::TCPServerTest::test_handle_stream_coroutine_logging\nPASSED r2e_tests.test_1::TCPServerTest::test_handle_stream_native_coroutine\nPASSED r2e_tests.test_1::TCPServerTest::test_stop_twice\n=================== 3 passed in 0.00s ===================\n",
    "new_commit_res_stderr": "",
    "old_commit_res_code": 1,
    "old_commit_res_stdout": "============================= test session starts =============================\nplatform linux -- Python 3.9.21\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_cadb2e4f7fc6227113d78ae4e9361f72de66622a\n...\ncollected 3 items\n\n=================================== FAILURES ===================================\n__________ TCPServerTest.test_handle_stream_native_coroutine __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_cadb2e4f7fc6227113d78ae4e9361f72de66622a/tornado/testing.py\", line 136, in __call__\n    result = self.orig_method(*args, **kwargs)\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_cadb2e4f7fc6227113d78ae4e9361f72de66622a/tornado/testing.py\", line 527, in post_coroutine\n    return self.io_loop.run_sync(\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_cadb2e4f7fc6227113d78ae4e9361f72de66622a/tornado/ioloop.py\", line 458, in run_sync\n    return future_cell[0].result()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_cadb2e4f7fc6227113d78ae4e9361f72de66622a/tornado/concurrent.py\", line 237, in result\n    raise_exc_info(self._exc_info)\n  File \"<string>\", line 3, in raise_exc_info\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_cadb2e4f7fc6227113d78ae4e9361f72de66622a/tornado/gen.py\", line 1054, in run\n    yielded = self.gen.send(value)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/types.py\", line 215, in send\n    return self.__wrapped.send(val)\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_cadb2e4f7fc6227113d78ae4e9361f72de66622a/r2e_tests/test_1.py\", line 61, in test_handle_stream_native_coroutine\n    self.assertEqual(result, b'data')\nAssertionError: b'' != b'data'\n\n==================== short test summary info ====================\nPASSED r2e_tests.test_1::TCPServerTest::test_handle_stream_coroutine_logging\nFAILED r2e_tests.test_1::TCPServerTest::test_handle_stream_native_coroutine\nPASSED r2e_tests.test_1::TCPServerTest::test_stop_twice\n=================== 1 failed, 2 passed in 0.00s ===================\n",
    "old_commit_res_stderr": "ERROR:tornado.application:Error in connection callback\nTraceback (most recent call last):\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_cadb2e4f7fc6227113d78ae4e9361f72de66622a/tornado/tcpserver.py\", line 295, in _handle_connection\n    self.io_loop.add_future(future, lambda f: f.result())\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_cadb2e4f7fc6227113d78ae4e9361f72de66622a/tornado/ioloop.py\", line 594, in add_future\n    assert is_future(future)\nAssertionError\n"
}
tornado/tcpserver.py tornado/test/tcpserver_test.py
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** Native Coroutines in `handle_stream` Prevent Data from Being Sent

**Description:**
When `handle_stream` is implemented as a native coroutine, the server fails to send data to the client. Instead of receiving the expected data, the client receives an empty byte string.

**Example Buggy Code:**
```python
class TestServer(TCPServer):
    async def handle_stream(self, stream, address):
        stream.write(b'data')
        stream.close()

sock, port = bind_unused_port()
server = TestServer()
server.add_socket(sock)
client = IOStream(socket.socket())
client.connect(('localhost', port))
result = client.read_until_close()
print(result)  # Expected: b'data', but gets: b''
```

**Expected Behavior:**
When a native coroutine is used for `handle_stream`, the server should successfully write `b'data'` to the stream and properly close the connection. The client should receive `b'data'` as the response.

**Actual Behavior:**
Using a native coroutine for `handle_stream` results in the client receiving `b''` instead of the expected `b'data'`. This indicates that the data is not being sent correctly when `handle_stream` is a native coroutine.

[/ISSUE]
--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.

--- BEGIN FILE ---
```
### tornado/tcpserver.py
#!/usr/bin/env python
#
# Copyright 2011 Facebook
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

"""A non-blocking, single-threaded TCP server."""
from __future__ import absolute_import, division, print_function, with_statement

import errno
import os
import socket

from tornado.log import app_log
from tornado.ioloop import IOLoop
from tornado.iostream import IOStream, SSLIOStream
from tornado.netutil import bind_sockets, add_accept_handler, ssl_wrap_socket
from tornado import process
from tornado.util import errno_from_exception

try:
    import ssl
except ImportError:
    # ssl is not available on Google App Engine.
    ssl = None


class TCPServer(object):
    r"""A non-blocking, single-threaded TCP server.

    To use `TCPServer`, define a subclass which overrides the `handle_stream`
    method. For example, a simple echo server could be defined like this::

      from tornado.tcpserver import TCPServer
      from tornado.iostream import StreamClosedError
      from tornado import gen

      class EchoServer(TCPServer):
          @gen.coroutine
          def handle_stream(self, stream, address):
              while True:
                  try:
                      data = yield stream.read_until(b"\n")
                      yield stream.write(data)
                  except StreamClosedError:
                      break

    To make this server serve SSL traffic, send the ``ssl_options`` keyword
    argument with an `ssl.SSLContext` object. For compatibility with older
    versions of Python ``ssl_options`` may also be a dictionary of keyword
    arguments for the `ssl.wrap_socket` method.::

       ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
       ssl_ctx.load_cert_chain(os.path.join(data_dir, "mydomain.crt"),
                               os.path.join(data_dir, "mydomain.key"))
       TCPServer(ssl_options=ssl_ctx)

    `TCPServer` initialization follows one of three patterns:

    1. `listen`: simple single-process::

            server = TCPServer()
            server.listen(8888)
            IOLoop.current().start()

    2. `bind`/`start`: simple multi-process::

            server = TCPServer()
            server.bind(8888)
            server.start(0)  # Forks multiple sub-processes
            IOLoop.current().start()

       When using this interface, an `.IOLoop` must *not* be passed
       to the `TCPServer` constructor.  `start` will always start
       the server on the default singleton `.IOLoop`.

    3. `add_sockets`: advanced multi-process::

            sockets = bind_sockets(8888)
            tornado.process.fork_processes(0)
            server = TCPServer()
            server.add_sockets(sockets)
            IOLoop.current().start()

       The `add_sockets` interface is more complicated, but it can be
       used with `tornado.process.fork_processes` to give you more
       flexibility in when the fork happens.  `add_sockets` can
       also be used in single-process servers if you want to create
       your listening sockets in some way other than
       `~tornado.netutil.bind_sockets`.

    .. versionadded:: 3.1
       The ``max_buffer_size`` argument.
    """
    def __init__(self, io_loop=None, ssl_options=None, max_buffer_size=None,
                 read_chunk_size=None):
        self.io_loop = io_loop
        self.ssl_options = ssl_options
        self._sockets = {}  # fd -> socket object
        self._pending_sockets = []
        self._started = False
        self._stopped = False
        self.max_buffer_size = max_buffer_size
        self.read_chunk_size = read_chunk_size

        # Verify the SSL options. Otherwise we don't get errors until clients
        # connect. This doesn't verify that the keys are legitimate, but
        # the SSL module doesn't do that until there is a connected socket
        # which seems like too much work
        if self.ssl_options is not None and isinstance(self.ssl_options, dict):
            # Only certfile is required: it can contain both keys
            if 'certfile' not in self.ssl_options:
                raise KeyError('missing key "certfile" in ssl_options')

            if not os.path.exists(self.ssl_options['certfile']):
                raise ValueError('certfile "%s" does not exist' %
                                 self.ssl_options['certfile'])
            if ('keyfile' in self.ssl_options and
                    not os.path.exists(self.ssl_options['keyfile'])):
                raise ValueError('keyfile "%s" does not exist' %
                                 self.ssl_options['keyfile'])

    def listen(self, port, address=""):
        """Starts accepting connections on the given port.

        This method may be called more than once to listen on multiple ports.
        `listen` takes effect immediately; it is not necessary to call
        `TCPServer.start` afterwards.  It is, however, necessary to start
        the `.IOLoop`.
        """
        sockets = bind_sockets(port, address=address)
        self.add_sockets(sockets)

    def add_sockets(self, sockets):
        """Makes this server start accepting connections on the given sockets.

        The ``sockets`` parameter is a list of socket objects such as
        those returned by `~tornado.netutil.bind_sockets`.
        `add_sockets` is typically used in combination with that
        method and `tornado.process.fork_processes` to provide greater
        control over the initialization of a multi-process server.
        """
        if self.io_loop is None:
            self.io_loop = IOLoop.current()

        for sock in sockets:
            self._sockets[sock.fileno()] = sock
            add_accept_handler(sock, self._handle_connection,
                               io_loop=self.io_loop)

    def add_socket(self, socket):
        """Singular version of `add_sockets`.  Takes a single socket object."""
        self.add_sockets([socket])

    def bind(self, port, address=None, family=socket.AF_UNSPEC, backlog=128,
             reuse_port=False):
        """Binds this server to the given port on the given address.

        To start the server, call `start`. If you want to run this server
        in a single process, you can call `listen` as a shortcut to the
        sequence of `bind` and `start` calls.

        Address may be either an IP address or hostname.  If it's a hostname,
        the server will listen on all IP addresses associated with the
        name.  Address may be an empty string or None to listen on all
        available interfaces.  Family may be set to either `socket.AF_INET`
        or `socket.AF_INET6` to restrict to IPv4 or IPv6 addresses, otherwise
        both will be used if available.

        The ``backlog`` argument has the same meaning as for
        `socket.listen <socket.socket.listen>`. The ``reuse_port`` argument
        has the same meaning as for `.bind_sockets`.

        This method may be called multiple times prior to `start` to listen
        on multiple ports or interfaces.

        .. versionchanged:: 4.4
           Added the ``reuse_port`` argument.
        """
        sockets = bind_sockets(port, address=address, family=family,
                               backlog=backlog, reuse_port=reuse_port)
        if self._started:
            self.add_sockets(sockets)
        else:
            self._pending_sockets.extend(sockets)

    def start(self, num_processes=1):
        """Starts this server in the `.IOLoop`.

        By default, we run the server in this process and do not fork any
        additional child process.

        If num_processes is ``None`` or <= 0, we detect the number of cores
        available on this machine and fork that number of child
        processes. If num_processes is given and > 1, we fork that
        specific number of sub-processes.

        Since we use processes and not threads, there is no shared memory
        between any server code.

        Note that multiple processes are not compatible with the autoreload
        module (or the ``autoreload=True`` option to `tornado.web.Application`
        which defaults to True when ``debug=True``).
        When using multiple processes, no IOLoops can be created or
        referenced until after the call to ``TCPServer.start(n)``.
        """
        assert not self._started
        self._started = True
        if num_processes != 1:
            process.fork_processes(num_processes)
        sockets = self._pending_sockets
        self._pending_sockets = []
        self.add_sockets(sockets)

    def stop(self):
        """Stops listening for new connections.

        Requests currently in progress may still continue after the
        server is stopped.
        """
        if self._stopped:
            return
        self._stopped = True
        for fd, sock in self._sockets.items():
            assert sock.fileno() == fd
            self.io_loop.remove_handler(fd)
            sock.close()

    def handle_stream(self, stream, address):
        """Override to handle a new `.IOStream` from an incoming connection.

        This method may be a coroutine; if so any exceptions it raises
        asynchronously will be logged. Accepting of incoming connections
        will not be blocked by this coroutine.

        If this `TCPServer` is configured for SSL, ``handle_stream``
        may be called before the SSL handshake has completed. Use
        `.SSLIOStream.wait_for_handshake` if you need to verify the client's
        certificate or use NPN/ALPN.

        .. versionchanged:: 4.2
           Added the option for this method to be a coroutine.
        """
        raise NotImplementedError()

    def _handle_connection(self, connection, address):
        if self.ssl_options is not None:
            assert ssl, "Python 2.6+ and OpenSSL required for SSL"
            try:
                connection = ssl_wrap_socket(connection,
                                             self.ssl_options,
                                             server_side=True,
                                             do_handshake_on_connect=False)
            except ssl.SSLError as err:
                if err.args[0] == ssl.SSL_ERROR_EOF:
                    return connection.close()
                else:
                    raise
            except socket.error as err:
                # If the connection is closed immediately after it is created
                # (as in a port scan), we can get one of several errors.
                # wrap_socket makes an internal call to getpeername,
                # which may return either EINVAL (Mac OS X) or ENOTCONN
                # (Linux).  If it returns ENOTCONN, this error is
                # silently swallowed by the ssl module, so we need to
                # catch another error later on (AttributeError in
                # SSLIOStream._do_ssl_handshake).
                # To test this behavior, try nmap with the -sT flag.
                # https://github.com/tornadoweb/tornado/pull/750
                if errno_from_exception(err) in (errno.ECONNABORTED, errno.EINVAL):
                    return connection.close()
                else:
                    raise
        try:
            if self.ssl_options is not None:
                stream = SSLIOStream(connection, io_loop=self.io_loop,
                                     max_buffer_size=self.max_buffer_size,
                                     read_chunk_size=self.read_chunk_size)
            else:
                stream = IOStream(connection, io_loop=self.io_loop,
                                  max_buffer_size=self.max_buffer_size,
                                  read_chunk_size=self.read_chunk_size)
            future = self.handle_stream(stream, address)
            if future is not None:
                self.io_loop.add_future(future, lambda f: f.result())
        except Exception:
            app_log.error("Error in connection callback", exc_info=True)

```
--- END FILE ---

Please first localize the bug based on the issue statement, and then generate *SEARCH/REPLACE* edits to fix the issue.

Every *SEARCH/REPLACE* edit must use this format:
1. The file path
2. The start of search block: <<<<<<< SEARCH
3. A contiguous chunk of lines to search for in the existing source code
4. The dividing line: =======
5. The lines to replace into the source code
6. The end of the replace block: >>>>>>> REPLACE

Here is an example:

```python
### mathweb/flask/app.py
<<<<<<< SEARCH
from flask import Flask
=======
import math
from flask import Flask
>>>>>>> REPLACE
```
</solution>

Please note that the *SEARCH/REPLACE* edit REQUIRES PROPER INDENTATION. If you would like to add the line '        print(x)', you must fully write that out, with all those spaces before the code!
Wrap each *SEARCH/REPLACE* edit in a code block as shown in the example above. If you have multiple *SEARCH/REPLACE* edits, use a separate code block for each one.
[ISSUE]
**Title:** Native Coroutines in `handle_stream` Prevent Data from Being Sent

**Description:**
When `handle_stream` is implemented as a native coroutine, the server fails to send data to the client. Instead of receiving the expected data, the client receives an empty byte string.

**Example Buggy Code:**
```python
class TestServer(TCPServer):
    async def handle_stream(self, stream, address):
        stream.write(b'data')
        stream.close()

sock, port = bind_unused_port()
server = TestServer()
server.add_socket(sock)
client = IOStream(socket.socket())
client.connect(('localhost', port))
result = client.read_until_close()
print(result)  # Expected: b'data', but gets: b''
```

**Expected Behavior:**
When a native coroutine is used for `handle_stream`, the server should successfully write `b'data'` to the stream and properly close the connection. The client should receive `b'data'` as the response.

**Actual Behavior:**
Using a native coroutine for `handle_stream` results in the client receiving `b''` instead of the expected `b'data'`. This indicates that the data is not being sent correctly when `handle_stream` is a native coroutine.

[/ISSUE]
{
    "TCPServerTest.test_handle_stream_coroutine_logging": "PASSED",
    "TCPServerTest.test_handle_stream_native_coroutine": "PASSED",
    "TCPServerTest.test_stop_twice": "PASSED"
}
diff --git a/tornado/tcpserver.py b/tornado/tcpserver.py
index 31f49359..ac666698 100644
--- a/tornado/tcpserver.py
+++ b/tornado/tcpserver.py
@@ -21,6 +21,7 @@ import errno
 import os
 import socket
 
+from tornado import gen
 from tornado.log import app_log
 from tornado.ioloop import IOLoop
 from tornado.iostream import IOStream, SSLIOStream
@@ -290,8 +291,10 @@ class TCPServer(object):
                 stream = IOStream(connection, io_loop=self.io_loop,
                                   max_buffer_size=self.max_buffer_size,
                                   read_chunk_size=self.read_chunk_size)
+
             future = self.handle_stream(stream, address)
             if future is not None:
-                self.io_loop.add_future(future, lambda f: f.result())
+                self.io_loop.add_future(gen.convert_yielded(future),
+                                        lambda f: f.result())
         except Exception:
             app_log.error("Error in connection callback", exc_info=True)

{"tornado/tcpserver.py": "#!/usr/bin/env python\n#\n# Copyright 2011 Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"A non-blocking, single-threaded TCP server.\"\"\"\nfrom __future__ import absolute_import, division, print_function, with_statement\n\nimport errno\nimport os\nimport socket\n\nfrom tornado.log import app_log\nfrom tornado.ioloop import IOLoop\nfrom tornado.iostream import IOStream, SSLIOStream\nfrom tornado.netutil import bind_sockets, add_accept_handler, ssl_wrap_socket\nfrom tornado import process\nfrom tornado.util import errno_from_exception\n\ntry:\n    import ssl\nexcept ImportError:\n    # ssl is not available on Google App Engine.\n    ssl = None\n\n\nclass TCPServer(object):\n    r\"\"\"A non-blocking, single-threaded TCP server.\n\n    To use `TCPServer`, define a subclass which overrides the `handle_stream`\n    method. For example, a simple echo server could be defined like this::\n\n      from tornado.tcpserver import TCPServer\n      from tornado.iostream import StreamClosedError\n      from tornado import gen\n\n      class EchoServer(TCPServer):\n          @gen.coroutine\n          def handle_stream(self, stream, address):\n              while True:\n                  try:\n                      data = yield stream.read_until(b\"\\n\")\n                      yield stream.write(data)\n                  except StreamClosedError:\n                      break\n\n    To make this server serve SSL traffic, send the ``ssl_options`` keyword\n    argument with an `ssl.SSLContext` object. For compatibility with older\n    versions of Python ``ssl_options`` may also be a dictionary of keyword\n    arguments for the `ssl.wrap_socket` method.::\n\n       ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)\n       ssl_ctx.load_cert_chain(os.path.join(data_dir, \"mydomain.crt\"),\n                               os.path.join(data_dir, \"mydomain.key\"))\n       TCPServer(ssl_options=ssl_ctx)\n\n    `TCPServer` initialization follows one of three patterns:\n\n    1. `listen`: simple single-process::\n\n            server = TCPServer()\n            server.listen(8888)\n            IOLoop.current().start()\n\n    2. `bind`/`start`: simple multi-process::\n\n            server = TCPServer()\n            server.bind(8888)\n            server.start(0)  # Forks multiple sub-processes\n            IOLoop.current().start()\n\n       When using this interface, an `.IOLoop` must *not* be passed\n       to the `TCPServer` constructor.  `start` will always start\n       the server on the default singleton `.IOLoop`.\n\n    3. `add_sockets`: advanced multi-process::\n\n            sockets = bind_sockets(8888)\n            tornado.process.fork_processes(0)\n            server = TCPServer()\n            server.add_sockets(sockets)\n            IOLoop.current().start()\n\n       The `add_sockets` interface is more complicated, but it can be\n       used with `tornado.process.fork_processes` to give you more\n       flexibility in when the fork happens.  `add_sockets` can\n       also be used in single-process servers if you want to create\n       your listening sockets in some way other than\n       `~tornado.netutil.bind_sockets`.\n\n    .. versionadded:: 3.1\n       The ``max_buffer_size`` argument.\n    \"\"\"\n    def __init__(self, io_loop=None, ssl_options=None, max_buffer_size=None,\n                 read_chunk_size=None):\n        self.io_loop = io_loop\n        self.ssl_options = ssl_options\n        self._sockets = {}  # fd -> socket object\n        self._pending_sockets = []\n        self._started = False\n        self._stopped = False\n        self.max_buffer_size = max_buffer_size\n        self.read_chunk_size = read_chunk_size\n\n        # Verify the SSL options. Otherwise we don't get errors until clients\n        # connect. This doesn't verify that the keys are legitimate, but\n        # the SSL module doesn't do that until there is a connected socket\n        # which seems like too much work\n        if self.ssl_options is not None and isinstance(self.ssl_options, dict):\n            # Only certfile is required: it can contain both keys\n            if 'certfile' not in self.ssl_options:\n                raise KeyError('missing key \"certfile\" in ssl_options')\n\n            if not os.path.exists(self.ssl_options['certfile']):\n                raise ValueError('certfile \"%s\" does not exist' %\n                                 self.ssl_options['certfile'])\n            if ('keyfile' in self.ssl_options and\n                    not os.path.exists(self.ssl_options['keyfile'])):\n                raise ValueError('keyfile \"%s\" does not exist' %\n                                 self.ssl_options['keyfile'])\n\n    def listen(self, port, address=\"\"):\n        \"\"\"Starts accepting connections on the given port.\n\n        This method may be called more than once to listen on multiple ports.\n        `listen` takes effect immediately; it is not necessary to call\n        `TCPServer.start` afterwards.  It is, however, necessary to start\n        the `.IOLoop`.\n        \"\"\"\n        sockets = bind_sockets(port, address=address)\n        self.add_sockets(sockets)\n\n    def add_sockets(self, sockets):\n        \"\"\"Makes this server start accepting connections on the given sockets.\n\n        The ``sockets`` parameter is a list of socket objects such as\n        those returned by `~tornado.netutil.bind_sockets`.\n        `add_sockets` is typically used in combination with that\n        method and `tornado.process.fork_processes` to provide greater\n        control over the initialization of a multi-process server.\n        \"\"\"\n        if self.io_loop is None:\n            self.io_loop = IOLoop.current()\n\n        for sock in sockets:\n            self._sockets[sock.fileno()] = sock\n            add_accept_handler(sock, self._handle_connection,\n                               io_loop=self.io_loop)\n\n    def add_socket(self, socket):\n        \"\"\"Singular version of `add_sockets`.  Takes a single socket object.\"\"\"\n        self.add_sockets([socket])\n\n    def bind(self, port, address=None, family=socket.AF_UNSPEC, backlog=128,\n             reuse_port=False):\n        \"\"\"Binds this server to the given port on the given address.\n\n        To start the server, call `start`. If you want to run this server\n        in a single process, you can call `listen` as a shortcut to the\n        sequence of `bind` and `start` calls.\n\n        Address may be either an IP address or hostname.  If it's a hostname,\n        the server will listen on all IP addresses associated with the\n        name.  Address may be an empty string or None to listen on all\n        available interfaces.  Family may be set to either `socket.AF_INET`\n        or `socket.AF_INET6` to restrict to IPv4 or IPv6 addresses, otherwise\n        both will be used if available.\n\n        The ``backlog`` argument has the same meaning as for\n        `socket.listen <socket.socket.listen>`. The ``reuse_port`` argument\n        has the same meaning as for `.bind_sockets`.\n\n        This method may be called multiple times prior to `start` to listen\n        on multiple ports or interfaces.\n\n        .. versionchanged:: 4.4\n           Added the ``reuse_port`` argument.\n        \"\"\"\n        sockets = bind_sockets(port, address=address, family=family,\n                               backlog=backlog, reuse_port=reuse_port)\n        if self._started:\n            self.add_sockets(sockets)\n        else:\n            self._pending_sockets.extend(sockets)\n\n    def start(self, num_processes=1):\n        \"\"\"Starts this server in the `.IOLoop`.\n\n        By default, we run the server in this process and do not fork any\n        additional child process.\n\n        If num_processes is ``None`` or <= 0, we detect the number of cores\n        available on this machine and fork that number of child\n        processes. If num_processes is given and > 1, we fork that\n        specific number of sub-processes.\n\n        Since we use processes and not threads, there is no shared memory\n        between any server code.\n\n        Note that multiple processes are not compatible with the autoreload\n        module (or the ``autoreload=True`` option to `tornado.web.Application`\n        which defaults to True when ``debug=True``).\n        When using multiple processes, no IOLoops can be created or\n        referenced until after the call to ``TCPServer.start(n)``.\n        \"\"\"\n        assert not self._started\n        self._started = True\n        if num_processes != 1:\n            process.fork_processes(num_processes)\n        sockets = self._pending_sockets\n        self._pending_sockets = []\n        self.add_sockets(sockets)\n\n    def stop(self):\n        \"\"\"Stops listening for new connections.\n\n        Requests currently in progress may still continue after the\n        server is stopped.\n        \"\"\"\n        if self._stopped:\n            return\n        self._stopped = True\n        for fd, sock in self._sockets.items():\n            assert sock.fileno() == fd\n            self.io_loop.remove_handler(fd)\n            sock.close()\n\n    def handle_stream(self, stream, address):\n        \"\"\"Override to handle a new `.IOStream` from an incoming connection.\n\n        This method may be a coroutine; if so any exceptions it raises\n        asynchronously will be logged. Accepting of incoming connections\n        will not be blocked by this coroutine.\n\n        If this `TCPServer` is configured for SSL, ``handle_stream``\n        may be called before the SSL handshake has completed. Use\n        `.SSLIOStream.wait_for_handshake` if you need to verify the client's\n        certificate or use NPN/ALPN.\n\n        .. versionchanged:: 4.2\n           Added the option for this method to be a coroutine.\n        \"\"\"\n        raise NotImplementedError()\n\n    def _handle_connection(self, connection, address):\n        if self.ssl_options is not None:\n            assert ssl, \"Python 2.6+ and OpenSSL required for SSL\"\n            try:\n                connection = ssl_wrap_socket(connection,\n                                             self.ssl_options,\n                                             server_side=True,\n                                             do_handshake_on_connect=False)\n            except ssl.SSLError as err:\n                if err.args[0] == ssl.SSL_ERROR_EOF:\n                    return connection.close()\n                else:\n                    raise\n            except socket.error as err:\n                # If the connection is closed immediately after it is created\n                # (as in a port scan), we can get one of several errors.\n                # wrap_socket makes an internal call to getpeername,\n                # which may return either EINVAL (Mac OS X) or ENOTCONN\n                # (Linux).  If it returns ENOTCONN, this error is\n                # silently swallowed by the ssl module, so we need to\n                # catch another error later on (AttributeError in\n                # SSLIOStream._do_ssl_handshake).\n                # To test this behavior, try nmap with the -sT flag.\n                # https://github.com/tornadoweb/tornado/pull/750\n                if errno_from_exception(err) in (errno.ECONNABORTED, errno.EINVAL):\n                    return connection.close()\n                else:\n                    raise\n        try:\n            if self.ssl_options is not None:\n                stream = SSLIOStream(connection, io_loop=self.io_loop,\n                                     max_buffer_size=self.max_buffer_size,\n                                     read_chunk_size=self.read_chunk_size)\n            else:\n                stream = IOStream(connection, io_loop=self.io_loop,\n                                  max_buffer_size=self.max_buffer_size,\n                                  read_chunk_size=self.read_chunk_size)\n            future = self.handle_stream(stream, address)\n            if future is not None:\n                self.io_loop.add_future(future, lambda f: f.result())\n        except Exception:\n            app_log.error(\"Error in connection callback\", exc_info=True)\n"}
A user will ask you to solve a task. You should first draft your thinking process (inner monologue). Then, generate the solution.

Your response format must follow the template below:
<think>
Your thoughts or/and draft, like working through an exercise on scratch paper. Be as casual and as long as you want until you are confident to generate a correct solution.
</think>
<solution>
Final solution presented to the user.
</solution>
system
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** Native Coroutines in `handle_stream` Prevent Data from Being Sent

**Description:**
When `handle_stream` is implemented as a native coroutine, the server fails to send data to the client. Instead of receiving the expected data, the client receives an empty byte string.

**Example Buggy Code:**
```python
class TestServer(TCPServer):
    async def handle_stream(self, stream, address):
        stream.write(b'data')
        stream.close()

sock, port = bind_unused_port()
server = TestServer()
server.add_socket(sock)
client = IOStream(socket.socket())
client.connect(('localhost', port))
result = client.read_until_close()
print(result)  # Expected: b'data', but gets: b''
```

**Expected Behavior:**
When a native coroutine is used for `handle_stream`, the server should successfully write `b'data'` to the stream and properly close the connection. The client should receive `b'data'` as the response.

**Actual Behavior:**
Using a native coroutine for `handle_stream` results in the client receiving `b''` instead of the expected `b'data'`. This indicates that the data is not being sent correctly when `handle_stream` is a native coroutine.

[/ISSUE]
--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.

--- BEGIN FILE ---
```
### tornado/tcpserver.py
#!/usr/bin/env python
#
# Copyright 2011 Facebook
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

"""A non-blocking, single-threaded TCP server."""
from __future__ import absolute_import, division, print_function, with_statement

import errno
import os
import socket

from tornado.log import app_log
from tornado.ioloop import IOLoop
from tornado.iostream import IOStream, SSLIOStream
from tornado.netutil import bind_sockets, add_accept_handler, ssl_wrap_socket
from tornado import process
from tornado.util import errno_from_exception

try:
    import ssl
except ImportError:
    # ssl is not available on Google App Engine.
    ssl = None


class TCPServer(object):
    r"""A non-blocking, single-threaded TCP server.

    To use `TCPServer`, define a subclass which overrides the `handle_stream`
    method. For example, a simple echo server could be defined like this::

      from tornado.tcpserver import TCPServer
      from tornado.iostream import StreamClosedError
      from tornado import gen

      class EchoServer(TCPServer):
          @gen.coroutine
          def handle_stream(self, stream, address):
              while True:
                  try:
                      data = yield stream.read_until(b"\n")
                      yield stream.write(data)
                  except StreamClosedError:
                      break

    To make this server serve SSL traffic, send the ``ssl_options`` keyword
    argument with an `ssl.SSLContext` object. For compatibility with older
    versions of Python ``ssl_options`` may also be a dictionary of keyword
    arguments for the `ssl.wrap_socket` method.::

       ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
       ssl_ctx.load_cert_chain(os.path.join(data_dir, "mydomain.crt"),
                               os.path.join(data_dir, "mydomain.key"))
       TCPServer(ssl_options=ssl_ctx)

    `TCPServer` initialization follows one of three patterns:

    1. `listen`: simple single-process::

            server = TCPServer()
            server.listen(8888)
            IOLoop.current().start()

    2. `bind`/`start`: simple multi-process::

            server = TCPServer()
            server.bind(8888)
            server.start(0)  # Forks multiple sub-processes
            IOLoop.current().start()

       When using this interface, an `.IOLoop` must *not* be passed
       to the `TCPServer` constructor.  `start` will always start
       the server on the default singleton `.IOLoop`.

    3. `add_sockets`: advanced multi-process::

            sockets = bind_sockets(8888)
            tornado.process.fork_processes(0)
            server = TCPServer()
            server.add_sockets(sockets)
            IOLoop.current().start()

       The `add_sockets` interface is more complicated, but it can be
       used with `tornado.process.fork_processes` to give you more
       flexibility in when the fork happens.  `add_sockets` can
       also be used in single-process servers if you want to create
       your listening sockets in some way other than
       `~tornado.netutil.bind_sockets`.

    .. versionadded:: 3.1
       The ``max_buffer_size`` argument.
    """
    def __init__(self, io_loop=None, ssl_options=None, max_buffer_size=None,
                 read_chunk_size=None):
        self.io_loop = io_loop
        self.ssl_options = ssl_options
        self._sockets = {}  # fd -> socket object
        self._pending_sockets = []
        self._started = False
        self._stopped = False
        self.max_buffer_size = max_buffer_size
        self.read_chunk_size = read_chunk_size

        # Verify the SSL options. Otherwise we don't get errors until clients
        # connect. This doesn't verify that the keys are legitimate, but
        # the SSL module doesn't do that until there is a connected socket
        # which seems like too much work
        if self.ssl_options is not None and isinstance(self.ssl_options, dict):
            # Only certfile is required: it can contain both keys
            if 'certfile' not in self.ssl_options:
                raise KeyError('missing key "certfile" in ssl_options')

            if not os.path.exists(self.ssl_options['certfile']):
                raise ValueError('certfile "%s" does not exist' %
                                 self.ssl_options['certfile'])
            if ('keyfile' in self.ssl_options and
                    not os.path.exists(self.ssl_options['keyfile'])):
                raise ValueError('keyfile "%s" does not exist' %
                                 self.ssl_options['keyfile'])

    def listen(self, port, address=""):
        """Starts accepting connections on the given port.

        This method may be called more than once to listen on multiple ports.
        `listen` takes effect immediately; it is not necessary to call
        `TCPServer.start` afterwards.  It is, however, necessary to start
        the `.IOLoop`.
        """
        sockets = bind_sockets(port, address=address)
        self.add_sockets(sockets)

    def add_sockets(self, sockets):
        """Makes this server start accepting connections on the given sockets.

        The ``sockets`` parameter is a list of socket objects such as
        those returned by `~tornado.netutil.bind_sockets`.
        `add_sockets` is typically used in combination with that
        method and `tornado.process.fork_processes` to provide greater
        control over the initialization of a multi-process server.
        """
        if self.io_loop is None:
            self.io_loop = IOLoop.current()

        for sock in sockets:
            self._sockets[sock.fileno()] = sock
            add_accept_handler(sock, self._handle_connection,
                               io_loop=self.io_loop)

    def add_socket(self, socket):
        """Singular version of `add_sockets`.  Takes a single socket object."""
        self.add_sockets([socket])

    def bind(self, port, address=None, family=socket.AF_UNSPEC, backlog=128,
             reuse_port=False):
        """Binds this server to the given port on the given address.

        To start the server, call `start`. If you want to run this server
        in a single process, you can call `listen` as a shortcut to the
        sequence of `bind` and `start` calls.

        Address may be either an IP address or hostname.  If it's a hostname,
        the server will listen on all IP addresses associated with the
        name.  Address may be an empty string or None to listen on all
        available interfaces.  Family may be set to either `socket.AF_INET`
        or `socket.AF_INET6` to restrict to IPv4 or IPv6 addresses, otherwise
        both will be used if available.

        The ``backlog`` argument has the same meaning as for
        `socket.listen <socket.socket.listen>`. The ``reuse_port`` argument
        has the same meaning as for `.bind_sockets`.

        This method may be called multiple times prior to `start` to listen
        on multiple ports or interfaces.

        .. versionchanged:: 4.4
           Added the ``reuse_port`` argument.
        """
        sockets = bind_sockets(port, address=address, family=family,
                               backlog=backlog, reuse_port=reuse_port)
        if self._started:
            self.add_sockets(sockets)
        else:
            self._pending_sockets.extend(sockets)

    def start(self, num_processes=1):
        """Starts this server in the `.IOLoop`.

        By default, we run the server in this process and do not fork any
        additional child process.

        If num_processes is ``None`` or <= 0, we detect the number of cores
        available on this machine and fork that number of child
        processes. If num_processes is given and > 1, we fork that
        specific number of sub-processes.

        Since we use processes and not threads, there is no shared memory
        between any server code.

        Note that multiple processes are not compatible with the autoreload
        module (or the ``autoreload=True`` option to `tornado.web.Application`
        which defaults to True when ``debug=True``).
        When using multiple processes, no IOLoops can be created or
        referenced until after the call to ``TCPServer.start(n)``.
        """
        assert not self._started
        self._started = True
        if num_processes != 1:
            process.fork_processes(num_processes)
        sockets = self._pending_sockets
        self._pending_sockets = []
        self.add_sockets(sockets)

    def stop(self):
        """Stops listening for new connections.

        Requests currently in progress may still continue after the
        server is stopped.
        """
        if self._stopped:
            return
        self._stopped = True
        for fd, sock in self._sockets.items():
            assert sock.fileno() == fd
            self.io_loop.remove_handler(fd)
            sock.close()

    def handle_stream(self, stream, address):
        """Override to handle a new `.IOStream` from an incoming connection.

        This method may be a coroutine; if so any exceptions it raises
        asynchronously will be logged. Accepting of incoming connections
        will not be blocked by this coroutine.

        If this `TCPServer` is configured for SSL, ``handle_stream``
        may be called before the SSL handshake has completed. Use
        `.SSLIOStream.wait_for_handshake` if you need to verify the client's
        certificate or use NPN/ALPN.

        .. versionchanged:: 4.2
           Added the option for this method to be a coroutine.
        """
        raise NotImplementedError()

    def _handle_connection(self, connection, address):
        if self.ssl_options is not None:
            assert ssl, "Python 2.6+ and OpenSSL required for SSL"
            try:
                connection = ssl_wrap_socket(connection,
                                             self.ssl_options,
                                             server_side=True,
                                             do_handshake_on_connect=False)
            except ssl.SSLError as err:
                if err.args[0] == ssl.SSL_ERROR_EOF:
                    return connection.close()
                else:
                    raise
            except socket.error as err:
                # If the connection is closed immediately after it is created
                # (as in a port scan), we can get one of several errors.
                # wrap_socket makes an internal call to getpeername,
                # which may return either EINVAL (Mac OS X) or ENOTCONN
                # (Linux).  If it returns ENOTCONN, this error is
                # silently swallowed by the ssl module, so we need to
                # catch another error later on (AttributeError in
                # SSLIOStream._do_ssl_handshake).
                # To test this behavior, try nmap with the -sT flag.
                # https://github.com/tornadoweb/tornado/pull/750
                if errno_from_exception(err) in (errno.ECONNABORTED, errno.EINVAL):
                    return connection.close()
                else:
                    raise
        try:
            if self.ssl_options is not None:
                stream = SSLIOStream(connection, io_loop=self.io_loop,
                                     max_buffer_size=self.max_buffer_size,
                                     read_chunk_size=self.read_chunk_size)
            else:
                stream = IOStream(connection, io_loop=self.io_loop,
                                  max_buffer_size=self.max_buffer_size,
                                  read_chunk_size=self.read_chunk_size)
            future = self.handle_stream(stream, address)
            if future is not None:
                self.io_loop.add_future(future, lambda f: f.result())
        except Exception:
            app_log.error("Error in connection callback", exc_info=True)

```
--- END FILE ---

Please first localize the bug based on the issue statement, and then generate *SEARCH/REPLACE* edits to fix the issue.

Every *SEARCH/REPLACE* edit must use this format:
1. The file path
2. The start of search block: <<<<<<< SEARCH
3. A contiguous chunk of lines to search for in the existing source code
4. The dividing line: =======
5. The lines to replace into the source code
6. The end of the replace block: >>>>>>> REPLACE

Here is an example:

```python
### mathweb/flask/app.py
<<<<<<< SEARCH
from flask import Flask
=======
import math
from flask import Flask
>>>>>>> REPLACE
```
</solution>

Please note that the *SEARCH/REPLACE* edit REQUIRES PROPER INDENTATION. If you would like to add the line '        print(x)', you must fully write that out, with all those spaces before the code!
Wrap each *SEARCH/REPLACE* edit in a code block as shown in the example above. If you have multiple *SEARCH/REPLACE* edits, use a separate code block for each one.
user