We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
YCM runs on large-ish non-source files, spews a backtrace when you enter insert mode
STR:

```
# Create a file that's large, but not so large as to cause ycm to disable itself
$ cd `mktemp -d`
$ dd if=/dev/urandom of=test bs=500k count=1
$ vim test
```

Now enter insert mode.

Result: YCM error spew, included below.

I bisected the test file size and noticed that the error starts occurring somewhere between files of size 100k and 300k.

```
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/usr/lib/youcompleteme/autoload/../python/ycm/youcompleteme.py",
line 255, in NativeFiletypeCompletionUsable
    self.NativeFiletypeCompletionAvailable() )
  File "/usr/lib/youcompleteme/autoload/../python/ycm/youcompleteme.py",
line 250, in NativeFiletypeCompletionAvailable
    vimsupport.CurrentFiletypes() ] )
  File "/usr/lib/youcompleteme/autoload/../python/ycm/youcompleteme.py",
line 240, in FiletypeCompleterExistsForFiletype
    exists_completer = SendCompleterAvailableRequest( filetype )
  File "/usr/lib/youcompleteme/autoload/../python/ycm/client/completer_available_request.py",
line 57, in SendCompleterAvailableRequest
    request.Start()
  File "/usr/lib/youcompleteme/autoload/../python/ycm/client/completer_available_request.py",
line 45, in Start
    'semantic_completion_available' )
  File "/usr/lib/youcompleteme/autoload/../python/ycm/client/base_request.py",
line 81, in PostDataToHandler
    timeout ) )
  File "/usr/lib/youcompleteme/autoload/../python/ycm/client/base_request.py",
line 177, in JsonFromFuture
    _ValidateResponseObject( response )
  File "/usr/lib/youcompleteme/autoload/../python/ycm/client/base_request.py",
line 206, in _ValidateResponseObject
    their_hmac = ToBytes( b64decode( response.headers[ _HMAC_HEADER ] ) )
  File "/usr/lib/youcompleteme/third_party/ycmd/third_party/requests/requests/structures.py",
line 54, in __getitem__
    return self._store[key.lower()][1]
KeyError: u'x-ycm-hmac'
E858: Eval did not return a valid python object

```

+@r4nt


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `ycmd/handlers.py`
Content:
```
1 # Copyright (C) 2013 Google Inc.
2 #
3 # This file is part of ycmd.
4 #
5 # ycmd is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # ycmd is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with ycmd.  If not, see <http://www.gnu.org/licenses/>.
17 
18 from __future__ import absolute_import
19 from __future__ import unicode_literals
20 from __future__ import print_function
21 from __future__ import division
22 from future import standard_library
23 standard_library.install_aliases()
24 from builtins import *  # noqa
25 
26 import atexit
27 import bottle
28 import http.client
29 import json
30 import logging
31 import traceback
32 from bottle import request
33 
34 import ycm_core
35 from ycmd import extra_conf_store, hmac_plugin, server_state, user_options_store
36 from ycmd.responses import BuildExceptionResponse, BuildCompletionResponse
37 from ycmd.request_wrap import RequestWrap
38 from ycmd.bottle_utils import SetResponseHeader
39 from ycmd.completers.completer_utils import FilterAndSortCandidatesWrap
40 
41 
42 # num bytes for the request body buffer; request.json only works if the request
43 # size is less than this
44 bottle.Request.MEMFILE_MAX = 1000 * 1024
45 
46 _server_state = None
47 _hmac_secret = bytes()
48 _logger = logging.getLogger( __name__ )
49 app = bottle.Bottle()
50 
51 
52 @app.post( '/event_notification' )
53 def EventNotification():
54   _logger.info( 'Received event notification' )
55   request_data = RequestWrap( request.json )
56   event_name = request_data[ 'event_name' ]
57   _logger.debug( 'Event name: %s', event_name )
58 
59   event_handler = 'On' + event_name
60   getattr( _server_state.GetGeneralCompleter(), event_handler )( request_data )
61 
62   filetypes = request_data[ 'filetypes' ]
63   response_data = None
64   if _server_state.FiletypeCompletionUsable( filetypes ):
65     response_data = getattr( _server_state.GetFiletypeCompleter( filetypes ),
66                              event_handler )( request_data )
67 
68   if response_data:
69     return _JsonResponse( response_data )
70   return _JsonResponse( {} )
71 
72 
73 @app.post( '/run_completer_command' )
74 def RunCompleterCommand():
75   _logger.info( 'Received command request' )
76   request_data = RequestWrap( request.json )
77   completer = _GetCompleterForRequestData( request_data )
78 
79   return _JsonResponse( completer.OnUserCommand(
80       request_data[ 'command_arguments' ],
81       request_data ) )
82 
83 
84 @app.post( '/completions' )
85 def GetCompletions():
86   _logger.info( 'Received completion request' )
87   request_data = RequestWrap( request.json )
88   ( do_filetype_completion, forced_filetype_completion ) = (
89                     _server_state.ShouldUseFiletypeCompleter( request_data ) )
90   _logger.debug( 'Using filetype completion: %s', do_filetype_completion )
91 
92   errors = None
93   completions = None
94 
95   if do_filetype_completion:
96     try:
97       completions = ( _server_state.GetFiletypeCompleter(
98                                   request_data[ 'filetypes' ] )
99                                  .ComputeCandidates( request_data ) )
100 
101     except Exception as exception:
102       if forced_filetype_completion:
103         # user explicitly asked for semantic completion, so just pass the error
104         # back
105         raise
106       else:
107         # store the error to be returned with results from the identifier
108         # completer
109         stack = traceback.format_exc()
110         _logger.error( 'Exception from semantic completer (using general): ' +
111                         "".join( stack ) )
112         errors = [ BuildExceptionResponse( exception, stack ) ]
113 
114   if not completions and not forced_filetype_completion:
115     completions = ( _server_state.GetGeneralCompleter()
116                                  .ComputeCandidates( request_data ) )
117 
118   return _JsonResponse(
119       BuildCompletionResponse( completions if completions else [],
120                                request_data.CompletionStartColumn(),
121                                errors = errors ) )
122 
123 
124 @app.post( '/filter_and_sort_candidates' )
125 def FilterAndSortCandidates():
126   _logger.info( 'Received filter & sort request' )
127   # Not using RequestWrap because no need and the requests coming in aren't like
128   # the usual requests we handle.
129   request_data = request.json
130 
131   return _JsonResponse( FilterAndSortCandidatesWrap(
132     request_data[ 'candidates'],
133     request_data[ 'sort_property' ],
134     request_data[ 'query' ] ) )
135 
136 
137 @app.get( '/healthy' )
138 def GetHealthy():
139   _logger.info( 'Received health request' )
140   if request.query.include_subservers:
141     cs_completer = _server_state.GetFiletypeCompleter( ['cs'] )
142     return _JsonResponse( cs_completer.ServerIsHealthy() )
143   return _JsonResponse( True )
144 
145 
146 @app.get( '/ready' )
147 def GetReady():
148   _logger.info( 'Received ready request' )
149   if request.query.subserver:
150     filetype = request.query.subserver
151     return _JsonResponse( _IsSubserverReady( filetype ) )
152   if request.query.include_subservers:
153     return _JsonResponse( _IsSubserverReady( 'cs' ) )
154   return _JsonResponse( True )
155 
156 
157 def _IsSubserverReady( filetype ):
158   completer = _server_state.GetFiletypeCompleter( [filetype] )
159   return completer.ServerIsReady()
160 
161 
162 @app.post( '/semantic_completion_available' )
163 def FiletypeCompletionAvailable():
164   _logger.info( 'Received filetype completion available request' )
165   return _JsonResponse( _server_state.FiletypeCompletionAvailable(
166       RequestWrap( request.json )[ 'filetypes' ] ) )
167 
168 
169 @app.post( '/defined_subcommands' )
170 def DefinedSubcommands():
171   _logger.info( 'Received defined subcommands request' )
172   completer = _GetCompleterForRequestData( RequestWrap( request.json ) )
173 
174   return _JsonResponse( completer.DefinedSubcommands() )
175 
176 
177 @app.post( '/detailed_diagnostic' )
178 def GetDetailedDiagnostic():
179   _logger.info( 'Received detailed diagnostic request' )
180   request_data = RequestWrap( request.json )
181   completer = _GetCompleterForRequestData( request_data )
182 
183   return _JsonResponse( completer.GetDetailedDiagnostic( request_data ) )
184 
185 
186 @app.post( '/load_extra_conf_file' )
187 def LoadExtraConfFile():
188   _logger.info( 'Received extra conf load request' )
189   request_data = RequestWrap( request.json, validate = False )
190   extra_conf_store.Load( request_data[ 'filepath' ], force = True )
191 
192 
193 @app.post( '/ignore_extra_conf_file' )
194 def IgnoreExtraConfFile():
195   _logger.info( 'Received extra conf ignore request' )
196   request_data = RequestWrap( request.json, validate = False )
197   extra_conf_store.Disable( request_data[ 'filepath' ] )
198 
199 
200 @app.post( '/debug_info' )
201 def DebugInfo():
202   _logger.info( 'Received debug info request' )
203 
204   output = []
205   has_clang_support = ycm_core.HasClangSupport()
206   output.append( 'Server has Clang support compiled in: {0}'.format(
207     has_clang_support ) )
208 
209   if has_clang_support:
210     output.append( 'Clang version: ' + ycm_core.ClangVersion() )
211 
212   request_data = RequestWrap( request.json )
213   try:
214     output.append(
215         _GetCompleterForRequestData( request_data ).DebugInfo( request_data) )
216   except Exception:
217     _logger.debug( 'Exception in debug info request: '
218                    + traceback.format_exc() )
219 
220   return _JsonResponse( '\n'.join( output ) )
221 
222 
223 # The type of the param is Bottle.HTTPError
224 @app.error( http.client.INTERNAL_SERVER_ERROR )
225 def ErrorHandler( httperror ):
226   body = _JsonResponse( BuildExceptionResponse( httperror.exception,
227                                                 httperror.traceback ) )
228   hmac_plugin.SetHmacHeader( body, _hmac_secret )
229   return body
230 
231 
232 def _JsonResponse( data ):
233   SetResponseHeader( 'Content-Type', 'application/json' )
234   return json.dumps( data, default = _UniversalSerialize )
235 
236 
237 def _UniversalSerialize( obj ):
238   try:
239     serialized = obj.__dict__.copy()
240     serialized[ 'TYPE' ] = type( obj ).__name__
241     return serialized
242   except AttributeError:
243     return str( obj )
244 
245 
246 def _GetCompleterForRequestData( request_data ):
247   completer_target = request_data.get( 'completer_target', None )
248 
249   if completer_target == 'identifier':
250     return _server_state.GetGeneralCompleter().GetIdentifierCompleter()
251   elif completer_target == 'filetype_default' or not completer_target:
252     return _server_state.GetFiletypeCompleter( request_data[ 'filetypes' ] )
253   else:
254     return _server_state.GetFiletypeCompleter( [ completer_target ] )
255 
256 
257 @atexit.register
258 def ServerShutdown():
259   _logger.info( 'Server shutting down' )
260   if _server_state:
261     _server_state.Shutdown()
262     extra_conf_store.Shutdown()
263 
264 
265 def SetHmacSecret( hmac_secret ):
266   global _hmac_secret
267   _hmac_secret = hmac_secret
268 
269 
270 def UpdateUserOptions( options ):
271   global _server_state
272 
273   if not options:
274     return
275 
276   # This should never be passed in, but let's try to remove it just in case.
277   options.pop( 'hmac_secret', None )
278   user_options_store.SetAll( options )
279   _server_state = server_state.ServerState( options )
280 
281 
282 def SetServerStateToDefaults():
283   global _server_state, _logger
284   _logger = logging.getLogger( __name__ )
285   user_options_store.LoadDefaults()
286   _server_state = server_state.ServerState( user_options_store.GetAll() )
287   extra_conf_store.Reset()
288
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/ycmd/handlers.py b/ycmd/handlers.py
--- a/ycmd/handlers.py
+++ b/ycmd/handlers.py
@@ -25,7 +25,6 @@
 
 import atexit
 import bottle
-import http.client
 import json
 import logging
 import traceback
@@ -221,13 +220,15 @@
 
 
 # The type of the param is Bottle.HTTPError
-@app.error( http.client.INTERNAL_SERVER_ERROR )
 def ErrorHandler( httperror ):
   body = _JsonResponse( BuildExceptionResponse( httperror.exception,
                                                 httperror.traceback ) )
   hmac_plugin.SetHmacHeader( body, _hmac_secret )
   return body
 
+# For every error Bottle encounters it will use this as the default handler
+app.default_error_handler = ErrorHandler
+
 
 def _JsonResponse( data ):
   SetResponseHeader( 'Content-Type', 'application/json' )

{"golden_diff": "diff --git a/ycmd/handlers.py b/ycmd/handlers.py\n--- a/ycmd/handlers.py\n+++ b/ycmd/handlers.py\n@@ -25,7 +25,6 @@\n \n import atexit\n import bottle\n-import http.client\n import json\n import logging\n import traceback\n@@ -221,13 +220,15 @@\n \n \n # The type of the param is Bottle.HTTPError\n-@app.error( http.client.INTERNAL_SERVER_ERROR )\n def ErrorHandler( httperror ):\n   body = _JsonResponse( BuildExceptionResponse( httperror.exception,\n                                                 httperror.traceback ) )\n   hmac_plugin.SetHmacHeader( body, _hmac_secret )\n   return body\n \n+# For every error Bottle encounters it will use this as the default handler\n+app.default_error_handler = ErrorHandler\n+\n \n def _JsonResponse( data ):\n   SetResponseHeader( 'Content-Type', 'application/json' )\n", "issue": "YCM runs on large-ish non-source files, spews a backtrace when you enter insert mode\nSTR:\n\n```\n# Create a file that's large, but not so large as to cause ycm to disable itself\n$ cd `mktemp -d`\n$ dd if=/dev/urandom of=test bs=500k count=1\n$ vim test\n```\n\nNow enter insert mode.\n\nResult: YCM error spew, included below.\n\nI bisected the test file size and noticed that the error starts occurring somewhere between files of size 100k and 300k.\n\n```\nTraceback (most recent call last):\n  File \"<string>\", line 1, in <module>\n  File \"/usr/lib/youcompleteme/autoload/../python/ycm/youcompleteme.py\",\nline 255, in NativeFiletypeCompletionUsable\n    self.NativeFiletypeCompletionAvailable() )\n  File \"/usr/lib/youcompleteme/autoload/../python/ycm/youcompleteme.py\",\nline 250, in NativeFiletypeCompletionAvailable\n    vimsupport.CurrentFiletypes() ] )\n  File \"/usr/lib/youcompleteme/autoload/../python/ycm/youcompleteme.py\",\nline 240, in FiletypeCompleterExistsForFiletype\n    exists_completer = SendCompleterAvailableRequest( filetype )\n  File \"/usr/lib/youcompleteme/autoload/../python/ycm/client/completer_available_request.py\",\nline 57, in SendCompleterAvailableRequest\n    request.Start()\n  File \"/usr/lib/youcompleteme/autoload/../python/ycm/client/completer_available_request.py\",\nline 45, in Start\n    'semantic_completion_available' )\n  File \"/usr/lib/youcompleteme/autoload/../python/ycm/client/base_request.py\",\nline 81, in PostDataToHandler\n    timeout ) )\n  File \"/usr/lib/youcompleteme/autoload/../python/ycm/client/base_request.py\",\nline 177, in JsonFromFuture\n    _ValidateResponseObject( response )\n  File \"/usr/lib/youcompleteme/autoload/../python/ycm/client/base_request.py\",\nline 206, in _ValidateResponseObject\n    their_hmac = ToBytes( b64decode( response.headers[ _HMAC_HEADER ] ) )\n  File \"/usr/lib/youcompleteme/third_party/ycmd/third_party/requests/requests/structures.py\",\nline 54, in __getitem__\n    return self._store[key.lower()][1]\nKeyError: u'x-ycm-hmac'\nE858: Eval did not return a valid python object\n\n```\n\n+@r4nt\n\n", "before_files": [{"content": "# Copyright (C) 2013 Google Inc.\n#\n# This file is part of ycmd.\n#\n# ycmd is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# ycmd is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with ycmd.  If not, see <http://www.gnu.org/licenses/>.\n\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\nfrom __future__ import print_function\nfrom __future__ import division\nfrom future import standard_library\nstandard_library.install_aliases()\nfrom builtins import *  # noqa\n\nimport atexit\nimport bottle\nimport http.client\nimport json\nimport logging\nimport traceback\nfrom bottle import request\n\nimport ycm_core\nfrom ycmd import extra_conf_store, hmac_plugin, server_state, user_options_store\nfrom ycmd.responses import BuildExceptionResponse, BuildCompletionResponse\nfrom ycmd.request_wrap import RequestWrap\nfrom ycmd.bottle_utils import SetResponseHeader\nfrom ycmd.completers.completer_utils import FilterAndSortCandidatesWrap\n\n\n# num bytes for the request body buffer; request.json only works if the request\n# size is less than this\nbottle.Request.MEMFILE_MAX = 1000 * 1024\n\n_server_state = None\n_hmac_secret = bytes()\n_logger = logging.getLogger( __name__ )\napp = bottle.Bottle()\n\n\n@app.post( '/event_notification' )\ndef EventNotification():\n  _logger.info( 'Received event notification' )\n  request_data = RequestWrap( request.json )\n  event_name = request_data[ 'event_name' ]\n  _logger.debug( 'Event name: %s', event_name )\n\n  event_handler = 'On' + event_name\n  getattr( _server_state.GetGeneralCompleter(), event_handler )( request_data )\n\n  filetypes = request_data[ 'filetypes' ]\n  response_data = None\n  if _server_state.FiletypeCompletionUsable( filetypes ):\n    response_data = getattr( _server_state.GetFiletypeCompleter( filetypes ),\n                             event_handler )( request_data )\n\n  if response_data:\n    return _JsonResponse( response_data )\n  return _JsonResponse( {} )\n\n\n@app.post( '/run_completer_command' )\ndef RunCompleterCommand():\n  _logger.info( 'Received command request' )\n  request_data = RequestWrap( request.json )\n  completer = _GetCompleterForRequestData( request_data )\n\n  return _JsonResponse( completer.OnUserCommand(\n      request_data[ 'command_arguments' ],\n      request_data ) )\n\n\n@app.post( '/completions' )\ndef GetCompletions():\n  _logger.info( 'Received completion request' )\n  request_data = RequestWrap( request.json )\n  ( do_filetype_completion, forced_filetype_completion ) = (\n                    _server_state.ShouldUseFiletypeCompleter( request_data ) )\n  _logger.debug( 'Using filetype completion: %s', do_filetype_completion )\n\n  errors = None\n  completions = None\n\n  if do_filetype_completion:\n    try:\n      completions = ( _server_state.GetFiletypeCompleter(\n                                  request_data[ 'filetypes' ] )\n                                 .ComputeCandidates( request_data ) )\n\n    except Exception as exception:\n      if forced_filetype_completion:\n        # user explicitly asked for semantic completion, so just pass the error\n        # back\n        raise\n      else:\n        # store the error to be returned with results from the identifier\n        # completer\n        stack = traceback.format_exc()\n        _logger.error( 'Exception from semantic completer (using general): ' +\n                        \"\".join( stack ) )\n        errors = [ BuildExceptionResponse( exception, stack ) ]\n\n  if not completions and not forced_filetype_completion:\n    completions = ( _server_state.GetGeneralCompleter()\n                                 .ComputeCandidates( request_data ) )\n\n  return _JsonResponse(\n      BuildCompletionResponse( completions if completions else [],\n                               request_data.CompletionStartColumn(),\n                               errors = errors ) )\n\n\n@app.post( '/filter_and_sort_candidates' )\ndef FilterAndSortCandidates():\n  _logger.info( 'Received filter & sort request' )\n  # Not using RequestWrap because no need and the requests coming in aren't like\n  # the usual requests we handle.\n  request_data = request.json\n\n  return _JsonResponse( FilterAndSortCandidatesWrap(\n    request_data[ 'candidates'],\n    request_data[ 'sort_property' ],\n    request_data[ 'query' ] ) )\n\n\n@app.get( '/healthy' )\ndef GetHealthy():\n  _logger.info( 'Received health request' )\n  if request.query.include_subservers:\n    cs_completer = _server_state.GetFiletypeCompleter( ['cs'] )\n    return _JsonResponse( cs_completer.ServerIsHealthy() )\n  return _JsonResponse( True )\n\n\n@app.get( '/ready' )\ndef GetReady():\n  _logger.info( 'Received ready request' )\n  if request.query.subserver:\n    filetype = request.query.subserver\n    return _JsonResponse( _IsSubserverReady( filetype ) )\n  if request.query.include_subservers:\n    return _JsonResponse( _IsSubserverReady( 'cs' ) )\n  return _JsonResponse( True )\n\n\ndef _IsSubserverReady( filetype ):\n  completer = _server_state.GetFiletypeCompleter( [filetype] )\n  return completer.ServerIsReady()\n\n\n@app.post( '/semantic_completion_available' )\ndef FiletypeCompletionAvailable():\n  _logger.info( 'Received filetype completion available request' )\n  return _JsonResponse( _server_state.FiletypeCompletionAvailable(\n      RequestWrap( request.json )[ 'filetypes' ] ) )\n\n\n@app.post( '/defined_subcommands' )\ndef DefinedSubcommands():\n  _logger.info( 'Received defined subcommands request' )\n  completer = _GetCompleterForRequestData( RequestWrap( request.json ) )\n\n  return _JsonResponse( completer.DefinedSubcommands() )\n\n\n@app.post( '/detailed_diagnostic' )\ndef GetDetailedDiagnostic():\n  _logger.info( 'Received detailed diagnostic request' )\n  request_data = RequestWrap( request.json )\n  completer = _GetCompleterForRequestData( request_data )\n\n  return _JsonResponse( completer.GetDetailedDiagnostic( request_data ) )\n\n\n@app.post( '/load_extra_conf_file' )\ndef LoadExtraConfFile():\n  _logger.info( 'Received extra conf load request' )\n  request_data = RequestWrap( request.json, validate = False )\n  extra_conf_store.Load( request_data[ 'filepath' ], force = True )\n\n\n@app.post( '/ignore_extra_conf_file' )\ndef IgnoreExtraConfFile():\n  _logger.info( 'Received extra conf ignore request' )\n  request_data = RequestWrap( request.json, validate = False )\n  extra_conf_store.Disable( request_data[ 'filepath' ] )\n\n\n@app.post( '/debug_info' )\ndef DebugInfo():\n  _logger.info( 'Received debug info request' )\n\n  output = []\n  has_clang_support = ycm_core.HasClangSupport()\n  output.append( 'Server has Clang support compiled in: {0}'.format(\n    has_clang_support ) )\n\n  if has_clang_support:\n    output.append( 'Clang version: ' + ycm_core.ClangVersion() )\n\n  request_data = RequestWrap( request.json )\n  try:\n    output.append(\n        _GetCompleterForRequestData( request_data ).DebugInfo( request_data) )\n  except Exception:\n    _logger.debug( 'Exception in debug info request: '\n                   + traceback.format_exc() )\n\n  return _JsonResponse( '\\n'.join( output ) )\n\n\n# The type of the param is Bottle.HTTPError\n@app.error( http.client.INTERNAL_SERVER_ERROR )\ndef ErrorHandler( httperror ):\n  body = _JsonResponse( BuildExceptionResponse( httperror.exception,\n                                                httperror.traceback ) )\n  hmac_plugin.SetHmacHeader( body, _hmac_secret )\n  return body\n\n\ndef _JsonResponse( data ):\n  SetResponseHeader( 'Content-Type', 'application/json' )\n  return json.dumps( data, default = _UniversalSerialize )\n\n\ndef _UniversalSerialize( obj ):\n  try:\n    serialized = obj.__dict__.copy()\n    serialized[ 'TYPE' ] = type( obj ).__name__\n    return serialized\n  except AttributeError:\n    return str( obj )\n\n\ndef _GetCompleterForRequestData( request_data ):\n  completer_target = request_data.get( 'completer_target', None )\n\n  if completer_target == 'identifier':\n    return _server_state.GetGeneralCompleter().GetIdentifierCompleter()\n  elif completer_target == 'filetype_default' or not completer_target:\n    return _server_state.GetFiletypeCompleter( request_data[ 'filetypes' ] )\n  else:\n    return _server_state.GetFiletypeCompleter( [ completer_target ] )\n\n\n@atexit.register\ndef ServerShutdown():\n  _logger.info( 'Server shutting down' )\n  if _server_state:\n    _server_state.Shutdown()\n    extra_conf_store.Shutdown()\n\n\ndef SetHmacSecret( hmac_secret ):\n  global _hmac_secret\n  _hmac_secret = hmac_secret\n\n\ndef UpdateUserOptions( options ):\n  global _server_state\n\n  if not options:\n    return\n\n  # This should never be passed in, but let's try to remove it just in case.\n  options.pop( 'hmac_secret', None )\n  user_options_store.SetAll( options )\n  _server_state = server_state.ServerState( options )\n\n\ndef SetServerStateToDefaults():\n  global _server_state, _logger\n  _logger = logging.getLogger( __name__ )\n  user_options_store.LoadDefaults()\n  _server_state = server_state.ServerState( user_options_store.GetAll() )\n  extra_conf_store.Reset()\n", "path": "ycmd/handlers.py"}], "after_files": [{"content": "# Copyright (C) 2013 Google Inc.\n#\n# This file is part of ycmd.\n#\n# ycmd is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# ycmd is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with ycmd.  If not, see <http://www.gnu.org/licenses/>.\n\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\nfrom __future__ import print_function\nfrom __future__ import division\nfrom future import standard_library\nstandard_library.install_aliases()\nfrom builtins import *  # noqa\n\nimport atexit\nimport bottle\nimport json\nimport logging\nimport traceback\nfrom bottle import request\n\nimport ycm_core\nfrom ycmd import extra_conf_store, hmac_plugin, server_state, user_options_store\nfrom ycmd.responses import BuildExceptionResponse, BuildCompletionResponse\nfrom ycmd.request_wrap import RequestWrap\nfrom ycmd.bottle_utils import SetResponseHeader\nfrom ycmd.completers.completer_utils import FilterAndSortCandidatesWrap\n\n\n# num bytes for the request body buffer; request.json only works if the request\n# size is less than this\nbottle.Request.MEMFILE_MAX = 1000 * 1024\n\n_server_state = None\n_hmac_secret = bytes()\n_logger = logging.getLogger( __name__ )\napp = bottle.Bottle()\n\n\n@app.post( '/event_notification' )\ndef EventNotification():\n  _logger.info( 'Received event notification' )\n  request_data = RequestWrap( request.json )\n  event_name = request_data[ 'event_name' ]\n  _logger.debug( 'Event name: %s', event_name )\n\n  event_handler = 'On' + event_name\n  getattr( _server_state.GetGeneralCompleter(), event_handler )( request_data )\n\n  filetypes = request_data[ 'filetypes' ]\n  response_data = None\n  if _server_state.FiletypeCompletionUsable( filetypes ):\n    response_data = getattr( _server_state.GetFiletypeCompleter( filetypes ),\n                             event_handler )( request_data )\n\n  if response_data:\n    return _JsonResponse( response_data )\n  return _JsonResponse( {} )\n\n\n@app.post( '/run_completer_command' )\ndef RunCompleterCommand():\n  _logger.info( 'Received command request' )\n  request_data = RequestWrap( request.json )\n  completer = _GetCompleterForRequestData( request_data )\n\n  return _JsonResponse( completer.OnUserCommand(\n      request_data[ 'command_arguments' ],\n      request_data ) )\n\n\n@app.post( '/completions' )\ndef GetCompletions():\n  _logger.info( 'Received completion request' )\n  request_data = RequestWrap( request.json )\n  ( do_filetype_completion, forced_filetype_completion ) = (\n                    _server_state.ShouldUseFiletypeCompleter( request_data ) )\n  _logger.debug( 'Using filetype completion: %s', do_filetype_completion )\n\n  errors = None\n  completions = None\n\n  if do_filetype_completion:\n    try:\n      completions = ( _server_state.GetFiletypeCompleter(\n                                  request_data[ 'filetypes' ] )\n                                 .ComputeCandidates( request_data ) )\n\n    except Exception as exception:\n      if forced_filetype_completion:\n        # user explicitly asked for semantic completion, so just pass the error\n        # back\n        raise\n      else:\n        # store the error to be returned with results from the identifier\n        # completer\n        stack = traceback.format_exc()\n        _logger.error( 'Exception from semantic completer (using general): ' +\n                        \"\".join( stack ) )\n        errors = [ BuildExceptionResponse( exception, stack ) ]\n\n  if not completions and not forced_filetype_completion:\n    completions = ( _server_state.GetGeneralCompleter()\n                                 .ComputeCandidates( request_data ) )\n\n  return _JsonResponse(\n      BuildCompletionResponse( completions if completions else [],\n                               request_data.CompletionStartColumn(),\n                               errors = errors ) )\n\n\n@app.post( '/filter_and_sort_candidates' )\ndef FilterAndSortCandidates():\n  _logger.info( 'Received filter & sort request' )\n  # Not using RequestWrap because no need and the requests coming in aren't like\n  # the usual requests we handle.\n  request_data = request.json\n\n  return _JsonResponse( FilterAndSortCandidatesWrap(\n    request_data[ 'candidates'],\n    request_data[ 'sort_property' ],\n    request_data[ 'query' ] ) )\n\n\n@app.get( '/healthy' )\ndef GetHealthy():\n  _logger.info( 'Received health request' )\n  if request.query.include_subservers:\n    cs_completer = _server_state.GetFiletypeCompleter( ['cs'] )\n    return _JsonResponse( cs_completer.ServerIsHealthy() )\n  return _JsonResponse( True )\n\n\n@app.get( '/ready' )\ndef GetReady():\n  _logger.info( 'Received ready request' )\n  if request.query.subserver:\n    filetype = request.query.subserver\n    return _JsonResponse( _IsSubserverReady( filetype ) )\n  if request.query.include_subservers:\n    return _JsonResponse( _IsSubserverReady( 'cs' ) )\n  return _JsonResponse( True )\n\n\ndef _IsSubserverReady( filetype ):\n  completer = _server_state.GetFiletypeCompleter( [filetype] )\n  return completer.ServerIsReady()\n\n\n@app.post( '/semantic_completion_available' )\ndef FiletypeCompletionAvailable():\n  _logger.info( 'Received filetype completion available request' )\n  return _JsonResponse( _server_state.FiletypeCompletionAvailable(\n      RequestWrap( request.json )[ 'filetypes' ] ) )\n\n\n@app.post( '/defined_subcommands' )\ndef DefinedSubcommands():\n  _logger.info( 'Received defined subcommands request' )\n  completer = _GetCompleterForRequestData( RequestWrap( request.json ) )\n\n  return _JsonResponse( completer.DefinedSubcommands() )\n\n\n@app.post( '/detailed_diagnostic' )\ndef GetDetailedDiagnostic():\n  _logger.info( 'Received detailed diagnostic request' )\n  request_data = RequestWrap( request.json )\n  completer = _GetCompleterForRequestData( request_data )\n\n  return _JsonResponse( completer.GetDetailedDiagnostic( request_data ) )\n\n\n@app.post( '/load_extra_conf_file' )\ndef LoadExtraConfFile():\n  _logger.info( 'Received extra conf load request' )\n  request_data = RequestWrap( request.json, validate = False )\n  extra_conf_store.Load( request_data[ 'filepath' ], force = True )\n\n\n@app.post( '/ignore_extra_conf_file' )\ndef IgnoreExtraConfFile():\n  _logger.info( 'Received extra conf ignore request' )\n  request_data = RequestWrap( request.json, validate = False )\n  extra_conf_store.Disable( request_data[ 'filepath' ] )\n\n\n@app.post( '/debug_info' )\ndef DebugInfo():\n  _logger.info( 'Received debug info request' )\n\n  output = []\n  has_clang_support = ycm_core.HasClangSupport()\n  output.append( 'Server has Clang support compiled in: {0}'.format(\n    has_clang_support ) )\n\n  if has_clang_support:\n    output.append( 'Clang version: ' + ycm_core.ClangVersion() )\n\n  request_data = RequestWrap( request.json )\n  try:\n    output.append(\n        _GetCompleterForRequestData( request_data ).DebugInfo( request_data) )\n  except Exception:\n    _logger.debug( 'Exception in debug info request: '\n                   + traceback.format_exc() )\n\n  return _JsonResponse( '\\n'.join( output ) )\n\n\n# The type of the param is Bottle.HTTPError\ndef ErrorHandler( httperror ):\n  body = _JsonResponse( BuildExceptionResponse( httperror.exception,\n                                                httperror.traceback ) )\n  hmac_plugin.SetHmacHeader( body, _hmac_secret )\n  return body\n\n# For every error Bottle encounters it will use this as the default handler\napp.default_error_handler = ErrorHandler\n\n\ndef _JsonResponse( data ):\n  SetResponseHeader( 'Content-Type', 'application/json' )\n  return json.dumps( data, default = _UniversalSerialize )\n\n\ndef _UniversalSerialize( obj ):\n  try:\n    serialized = obj.__dict__.copy()\n    serialized[ 'TYPE' ] = type( obj ).__name__\n    return serialized\n  except AttributeError:\n    return str( obj )\n\n\ndef _GetCompleterForRequestData( request_data ):\n  completer_target = request_data.get( 'completer_target', None )\n\n  if completer_target == 'identifier':\n    return _server_state.GetGeneralCompleter().GetIdentifierCompleter()\n  elif completer_target == 'filetype_default' or not completer_target:\n    return _server_state.GetFiletypeCompleter( request_data[ 'filetypes' ] )\n  else:\n    return _server_state.GetFiletypeCompleter( [ completer_target ] )\n\n\n@atexit.register\ndef ServerShutdown():\n  _logger.info( 'Server shutting down' )\n  if _server_state:\n    _server_state.Shutdown()\n    extra_conf_store.Shutdown()\n\n\ndef SetHmacSecret( hmac_secret ):\n  global _hmac_secret\n  _hmac_secret = hmac_secret\n\n\ndef UpdateUserOptions( options ):\n  global _server_state\n\n  if not options:\n    return\n\n  # This should never be passed in, but let's try to remove it just in case.\n  options.pop( 'hmac_secret', None )\n  user_options_store.SetAll( options )\n  _server_state = server_state.ServerState( options )\n\n\ndef SetServerStateToDefaults():\n  global _server_state, _logger\n  _logger = logging.getLogger( __name__ )\n  user_options_store.LoadDefaults()\n  _server_state = server_state.ServerState( user_options_store.GetAll() )\n  extra_conf_store.Reset()\n", "path": "ycmd/handlers.py"}]}