@vercel/python 4.4.0 → 4.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/package.json +1 -1
  2. package/vc_init.py +45 -2
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vercel/python",
3
- "version": "4.4.0",
3
+ "version": "4.5.0",
4
4
  "main": "./dist/index.js",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://vercel.com/docs/runtimes#official-runtimes/python",
package/vc_init.py CHANGED
@@ -28,7 +28,7 @@ def format_headers(headers, decode=False):
28
28
  return keyToList
29
29
 
30
30
  if 'VERCEL_IPC_FD' in os.environ:
31
- from http.server import HTTPServer
31
+ from http.server import ThreadingHTTPServer
32
32
  import http
33
33
  import time
34
34
  import contextvars
@@ -43,6 +43,49 @@ if 'VERCEL_IPC_FD' in os.environ:
43
43
  send_message = lambda message: sock.sendall((json.dumps(message) + '\0').encode())
44
44
  storage = contextvars.ContextVar('storage', default=None)
45
45
 
46
+ # Override urlopen from urllib3 (& requests) to send Request Metrics
47
+ try:
48
+ import urllib3
49
+ from urllib.parse import urlparse
50
+
51
+ def timed_request(func):
52
+ fetchId = 0
53
+ @functools.wraps(func)
54
+ def wrapper(self, method, url, *args, **kwargs):
55
+ nonlocal fetchId
56
+ fetchId += 1
57
+ start_time = int(time.time() * 1000)
58
+ result = func(self, method, url, *args, **kwargs)
59
+ elapsed_time = int(time.time() * 1000) - start_time
60
+ parsed_url = urlparse(url)
61
+ context = storage.get()
62
+ if context is not None:
63
+ send_message({
64
+ "type": "metric",
65
+ "payload": {
66
+ "context": {
67
+ "invocationId": context['invocationId'],
68
+ "requestId": context['requestId'],
69
+ },
70
+ "type": "fetch-metric",
71
+ "payload": {
72
+ "pathname": parsed_url.path,
73
+ "search": parsed_url.query,
74
+ "start": start_time,
75
+ "duration": elapsed_time,
76
+ "host": parsed_url.hostname or self.host,
77
+ "statusCode": result.status,
78
+ "method": method,
79
+ "id": fetchId
80
+ }
81
+ }
82
+ })
83
+ return result
84
+ return wrapper
85
+ urllib3.connectionpool.HTTPConnectionPool.urlopen = timed_request(urllib3.connectionpool.HTTPConnectionPool.urlopen)
86
+ except:
87
+ pass
88
+
46
89
  # Override sys.stdout and sys.stderr to map logs to the correct request
47
90
  class StreamWrapper:
48
91
  def __init__(self, stream, stream_name):
@@ -312,7 +355,7 @@ if 'VERCEL_IPC_FD' in os.environ:
312
355
  asyncio.run(app(scope, receive, send))
313
356
 
314
357
  if 'Handler' in locals():
315
- server = HTTPServer(('127.0.0.1', 0), Handler)
358
+ server = ThreadingHTTPServer(('127.0.0.1', 0), Handler)
316
359
  send_message({
317
360
  "type": "server-started",
318
361
  "payload": {