assassinlike commited on
Commit
b60e396
·
verified ·
1 Parent(s): 67d1255

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/__pycache__/__init__.cpython-311.pyc +0 -0
  2. data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/__pycache__/_version.cpython-311.pyc +0 -0
  3. data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/__pycache__/session.cpython-311.pyc +0 -0
  4. data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/dynamodb/__init__.py +0 -0
  5. data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/dynamodb/__pycache__/__init__.cpython-311.pyc +0 -0
  6. data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/dynamodb/__pycache__/table.cpython-311.pyc +0 -0
  7. data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/dynamodb/table.py +134 -0
  8. data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/experimental/__init__.py +0 -0
  9. data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/experimental/__pycache__/__init__.cpython-311.pyc +0 -0
  10. data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/experimental/__pycache__/async_chalice.cpython-311.pyc +0 -0
  11. data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/experimental/async_chalice.py +41 -0
  12. data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/resources/__init__.py +0 -0
  13. data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/resources/__pycache__/__init__.cpython-311.pyc +0 -0
  14. data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/resources/__pycache__/action.cpython-311.pyc +0 -0
  15. data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/resources/__pycache__/base.cpython-311.pyc +0 -0
  16. data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/resources/__pycache__/collection.cpython-311.pyc +0 -0
  17. data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/resources/__pycache__/factory.cpython-311.pyc +0 -0
  18. data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/resources/__pycache__/response.cpython-311.pyc +0 -0
  19. data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/resources/action.py +118 -0
  20. data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/resources/base.py +18 -0
  21. data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/resources/collection.py +189 -0
  22. data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/resources/factory.py +289 -0
  23. data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/resources/response.py +92 -0
  24. data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/s3/__init__.py +0 -0
  25. data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/s3/__pycache__/__init__.cpython-311.pyc +0 -0
  26. data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/s3/__pycache__/cse.cpython-311.pyc +0 -0
  27. data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/s3/__pycache__/inject.cpython-311.pyc +0 -0
  28. data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/s3/cse.py +614 -0
  29. data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/s3/inject.py +732 -0
  30. data/conda_envs/evalclaw/lib/python3.11/site-packages/h11/__pycache__/__init__.cpython-311.pyc +0 -0
  31. data/conda_envs/evalclaw/lib/python3.11/site-packages/h11/__pycache__/_abnf.cpython-311.pyc +0 -0
  32. data/conda_envs/evalclaw/lib/python3.11/site-packages/h11/__pycache__/_connection.cpython-311.pyc +0 -0
  33. data/conda_envs/evalclaw/lib/python3.11/site-packages/h11/__pycache__/_events.cpython-311.pyc +0 -0
  34. data/conda_envs/evalclaw/lib/python3.11/site-packages/h11/__pycache__/_headers.cpython-311.pyc +0 -0
  35. data/conda_envs/evalclaw/lib/python3.11/site-packages/h11/__pycache__/_readers.cpython-311.pyc +0 -0
  36. data/conda_envs/evalclaw/lib/python3.11/site-packages/h11/__pycache__/_receivebuffer.cpython-311.pyc +0 -0
  37. data/conda_envs/evalclaw/lib/python3.11/site-packages/h11/__pycache__/_state.cpython-311.pyc +0 -0
  38. data/conda_envs/evalclaw/lib/python3.11/site-packages/h11/__pycache__/_util.cpython-311.pyc +0 -0
  39. data/conda_envs/evalclaw/lib/python3.11/site-packages/h11/__pycache__/_version.cpython-311.pyc +0 -0
  40. data/conda_envs/evalclaw/lib/python3.11/site-packages/h11/__pycache__/_writers.cpython-311.pyc +0 -0
  41. data/conda_envs/evalclaw/lib/python3.11/site-packages/jiter/__pycache__/__init__.cpython-311.pyc +0 -0
  42. data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite-0.47.0.dist-info/licenses/LICENSE +24 -0
  43. data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite-0.47.0.dist-info/licenses/LICENSE.thirdparty +225 -0
  44. data/conda_envs/evalclaw/lib/python3.11/site-packages/lm_eval/_cli/__pycache__/__init__.cpython-311.pyc +0 -0
  45. data/conda_envs/evalclaw/lib/python3.11/site-packages/lm_eval/_cli/__pycache__/harness.cpython-311.pyc +0 -0
  46. data/conda_envs/evalclaw/lib/python3.11/site-packages/lm_eval/_cli/__pycache__/ls.cpython-311.pyc +0 -0
  47. data/conda_envs/evalclaw/lib/python3.11/site-packages/lm_eval/_cli/__pycache__/run.cpython-311.pyc +0 -0
  48. data/conda_envs/evalclaw/lib/python3.11/site-packages/lm_eval/_cli/__pycache__/subcommand.cpython-311.pyc +0 -0
  49. data/conda_envs/evalclaw/lib/python3.11/site-packages/lm_eval/_cli/__pycache__/utils.cpython-311.pyc +0 -0
  50. data/conda_envs/evalclaw/lib/python3.11/site-packages/lm_eval/_cli/__pycache__/validate.cpython-311.pyc +0 -0
data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (1.17 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/__pycache__/_version.cpython-311.pyc ADDED
Binary file (898 Bytes). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/__pycache__/session.cpython-311.pyc ADDED
Binary file (10.2 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/dynamodb/__init__.py ADDED
File without changes
data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/dynamodb/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (205 Bytes). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/dynamodb/__pycache__/table.cpython-311.pyc ADDED
Binary file (8.14 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/dynamodb/table.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import logging
3
+
4
+ from boto3.dynamodb.table import TableResource
5
+
6
+ logger = logging.getLogger(__name__)
7
+
8
+
9
+ def register_table_methods(base_classes, **kwargs):
10
+ base_classes.insert(0, CustomTableResource)
11
+
12
+
13
+ class CustomTableResource(TableResource):
14
+ def batch_writer(self, overwrite_by_pkeys=None, flush_amount=25, on_exit_loop_sleep=0):
15
+ return BatchWriter(
16
+ self.name, self.meta.client,
17
+ flush_amount=flush_amount,
18
+ overwrite_by_pkeys=overwrite_by_pkeys,
19
+ on_exit_loop_sleep=on_exit_loop_sleep
20
+ )
21
+
22
+
23
+ class BatchWriter(object):
24
+ """
25
+ Modified so that it does async
26
+ Automatically handle batch writes to DynamoDB for a single table.
27
+ """
28
+
29
+ def __init__(
30
+ self, table_name, client, flush_amount=25, overwrite_by_pkeys=None, on_exit_loop_sleep=0
31
+ ):
32
+ """
33
+
34
+ :type table_name: str
35
+ :param table_name: The name of the table. The class handles
36
+ batch writes to a single table.
37
+
38
+ :type client: ``botocore.client.Client``
39
+ :param client: A botocore client. Note this client
40
+ **must** have the dynamodb customizations applied
41
+ to it for transforming AttributeValues into the
42
+ wire protocol. What this means in practice is that
43
+ you need to use a client that comes from a DynamoDB
44
+ resource if you're going to instantiate this class
45
+ directly, i.e
46
+ ``boto3.resource('dynamodb').Table('foo').meta.client``.
47
+
48
+ :type flush_amount: int
49
+ :param flush_amount: The number of items to keep in
50
+ a local buffer before sending a batch_write_item
51
+ request to DynamoDB.
52
+
53
+ :type overwrite_by_pkeys: list(string)
54
+ :param overwrite_by_pkeys: De-duplicate request items in buffer
55
+ if match new request item on specified primary keys. i.e
56
+ ``["partition_key1", "sort_key2", "sort_key3"]``
57
+
58
+ :type on_exit_loop_sleep: int
59
+ :param on_exit_loop_sleep: When aexit is called by exiting the
60
+ context manager, if the value is > 0 then every time flush
61
+ is called a sleep will also be called.
62
+
63
+ """
64
+ self._table_name = table_name
65
+ self._client = client
66
+ self._items_buffer = []
67
+ self._flush_amount = flush_amount
68
+ self._overwrite_by_pkeys = overwrite_by_pkeys
69
+ self._on_exit_loop_sleep = on_exit_loop_sleep
70
+
71
+ async def put_item(self, Item):
72
+ await self._add_request_and_process({'PutRequest': {'Item': Item}})
73
+
74
+ async def delete_item(self, Key):
75
+ await self._add_request_and_process({'DeleteRequest': {'Key': Key}})
76
+
77
+ async def _add_request_and_process(self, request):
78
+ if self._overwrite_by_pkeys:
79
+ self._remove_dup_pkeys_request_if_any(request)
80
+ self._items_buffer.append(request)
81
+ await self._flush_if_needed()
82
+
83
+ def _remove_dup_pkeys_request_if_any(self, request):
84
+ pkey_values_new = self._extract_pkey_values(request)
85
+ for item in self._items_buffer:
86
+ if self._extract_pkey_values(item) == pkey_values_new:
87
+ self._items_buffer.remove(item)
88
+ logger.debug("With overwrite_by_pkeys enabled, skipping request:%s", item)
89
+
90
+ def _extract_pkey_values(self, request):
91
+ if request.get('PutRequest'):
92
+ return [
93
+ request['PutRequest']['Item'][key]
94
+ for key in self._overwrite_by_pkeys
95
+ ]
96
+ elif request.get('DeleteRequest'):
97
+ return [
98
+ request['DeleteRequest']['Key'][key]
99
+ for key in self._overwrite_by_pkeys
100
+ ]
101
+ return None
102
+
103
+ async def _flush_if_needed(self):
104
+ if len(self._items_buffer) >= self._flush_amount:
105
+ await self._flush()
106
+
107
+ async def _flush(self):
108
+ items_to_send = self._items_buffer[:self._flush_amount]
109
+ self._items_buffer = self._items_buffer[self._flush_amount:]
110
+ response = await self._client.batch_write_item(
111
+ RequestItems={self._table_name: items_to_send})
112
+ unprocessed_items = response['UnprocessedItems']
113
+
114
+ if not unprocessed_items:
115
+ unprocessed_items = {}
116
+ item_list = unprocessed_items.get(self._table_name, [])
117
+ # Any unprocessed_items are immediately added to the
118
+ # next batch we send.
119
+ self._items_buffer.extend(item_list)
120
+ logger.debug(
121
+ "Batch write sent %s, unprocessed: %s, buffer %s",
122
+ len(items_to_send), len(item_list), len(self._items_buffer)
123
+ )
124
+
125
+ async def __aenter__(self):
126
+ return self
127
+
128
+ async def __aexit__(self, exc_type, exc_value, tb):
129
+ # When we exit, we need to keep flushing whatever's left
130
+ # until there's nothing left in our items buffer.
131
+ while self._items_buffer:
132
+ await self._flush()
133
+ if self._items_buffer and self._on_exit_loop_sleep:
134
+ await asyncio.sleep(self._on_exit_loop_sleep)
data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/experimental/__init__.py ADDED
File without changes
data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/experimental/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (209 Bytes). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/experimental/__pycache__/async_chalice.cpython-311.pyc ADDED
Binary file (3.03 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/experimental/async_chalice.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ from typing import Optional
3
+
4
+ from chalice import Chalice
5
+ from chalice.app import RestAPIEventHandler
6
+
7
+ from aioboto3 import Session
8
+
9
+
10
+ class AsyncRestAPIEventHandler(RestAPIEventHandler):
11
+ def _get_view_function_response(self, view_function, function_args):
12
+ # Wrap the view_function so that we can return either the normal response
13
+ # or if its a co-routine, run it in an event loop first.
14
+ # Saves duplicating the whole function.
15
+ def _fake_view_function(**kwargs):
16
+ response = view_function(**kwargs)
17
+ if asyncio.iscoroutine(response):
18
+ # Always run in a new loop as chalice would close an existing one anyway
19
+ new_loop = asyncio.new_event_loop()
20
+ response = new_loop.run_until_complete(response)
21
+ new_loop.close()
22
+
23
+ return response
24
+ return super(AsyncRestAPIEventHandler, self)._get_view_function_response(_fake_view_function, function_args)
25
+
26
+
27
+ class AsyncChalice(Chalice):
28
+ def __init__(self, *args, aioboto3_session: Optional[Session] = None, **kwargs):
29
+ super(AsyncChalice, self).__init__(*args, **kwargs)
30
+
31
+ self.aioboto3 = aioboto3_session or Session()
32
+
33
+ def __call__(self, event, context):
34
+ self.lambda_context = context
35
+ handler = AsyncRestAPIEventHandler(
36
+ self.routes, self.api, self.log, self.debug,
37
+ middleware_handlers=self._get_middleware_handlers('http')
38
+ )
39
+ self.current_request = handler.create_request_object(event, context)
40
+ return handler(event, context)
41
+
data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/resources/__init__.py ADDED
File without changes
data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/resources/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (206 Bytes). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/resources/__pycache__/action.cpython-311.pyc ADDED
Binary file (5.39 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/resources/__pycache__/base.cpython-311.pyc ADDED
Binary file (1.52 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/resources/__pycache__/collection.cpython-311.pyc ADDED
Binary file (7.89 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/resources/__pycache__/factory.cpython-311.pyc ADDED
Binary file (9.65 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/resources/__pycache__/response.cpython-311.pyc ADDED
Binary file (3.74 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/resources/action.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+
3
+ from boto3.resources.action import ServiceAction, WaiterAction
4
+ from boto3.resources.params import create_request_parameters
5
+ from boto3.resources.action import xform_name
6
+
7
+ from aioboto3.resources.response import AIOResourceHandler, AIORawHandler
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+
12
+ class AIOServiceAction(ServiceAction):
13
+ def __init__(self, action_model, factory=None, service_context=None):
14
+ self._action_model = action_model
15
+
16
+ # In the simplest case we just return the response, but if a
17
+ # resource is defined, then we must create these before returning.
18
+ resource_response_model = action_model.resource
19
+ if resource_response_model:
20
+ self._response_handler = AIOResourceHandler(
21
+ search_path=resource_response_model.path,
22
+ factory=factory,
23
+ resource_model=resource_response_model,
24
+ service_context=service_context,
25
+ operation_name=action_model.request.operation
26
+ )
27
+ else:
28
+ self._response_handler = AIORawHandler(action_model.path)
29
+
30
+ async def __call__(self, parent, *args, **kwargs):
31
+ operation_name = xform_name(self._action_model.request.operation)
32
+
33
+ # First, build predefined params and then update with the
34
+ # user-supplied kwargs, which allows overriding the pre-built
35
+ # params if needed.
36
+ params = create_request_parameters(parent, self._action_model.request)
37
+ params.update(kwargs)
38
+
39
+ logger.debug('Calling %s:%s with %r', parent.meta.service_name,
40
+ operation_name, params)
41
+
42
+ response = await getattr(parent.meta.client, operation_name)(*args, **params)
43
+
44
+ logger.debug('Response: %r', response)
45
+
46
+ return await self._response_handler(parent, params, response)
47
+
48
+
49
+ class AioBatchAction(ServiceAction):
50
+ async def __call__(self, parent, *args, **kwargs):
51
+ service_name = None
52
+ client = None
53
+ responses = []
54
+ operation_name = xform_name(self._action_model.request.operation)
55
+
56
+ # Unlike the simple action above, a batch action must operate
57
+ # on batches (or pages) of items. So we get each page, construct
58
+ # the necessary parameters and call the batch operation.
59
+ async for page in parent.pages():
60
+ params = {}
61
+ for index, resource in enumerate(page):
62
+ # There is no public interface to get a service name
63
+ # or low-level client from a collection, so we get
64
+ # these from the first resource in the collection.
65
+ if service_name is None:
66
+ service_name = resource.meta.service_name
67
+ if client is None:
68
+ client = resource.meta.client
69
+
70
+ create_request_parameters(
71
+ resource, self._action_model.request,
72
+ params=params, index=index)
73
+
74
+ if not params:
75
+ # There are no items, no need to make a call.
76
+ break
77
+
78
+ params.update(kwargs)
79
+
80
+ logger.debug('Calling %s:%s with %r',
81
+ service_name, operation_name, params)
82
+
83
+ response = await (getattr(client, operation_name)(*args, **params))
84
+
85
+ logger.debug('Response: %r', response)
86
+
87
+ responses.append(
88
+ self._response_handler(parent, params, response))
89
+
90
+ return responses
91
+
92
+
93
+ class AIOWaiterAction(WaiterAction):
94
+ async def __call__(self, parent, *args, **kwargs):
95
+ """
96
+ Perform the wait operation after building operation
97
+ parameters.
98
+
99
+ :type parent: :py:class:`~boto3.resources.base.ServiceResource`
100
+ :param parent: The resource instance to which this action is attached.
101
+ """
102
+ client_waiter_name = xform_name(self._waiter_model.waiter_name)
103
+
104
+ # First, build predefined params and then update with the
105
+ # user-supplied kwargs, which allows overriding the pre-built
106
+ # params if needed.
107
+ params = create_request_parameters(parent, self._waiter_model)
108
+ params.update(kwargs)
109
+
110
+ logger.debug('Calling %s:%s with %r',
111
+ parent.meta.service_name,
112
+ self._waiter_resource_name, params)
113
+
114
+ client = parent.meta.client
115
+ waiter = client.get_waiter(client_waiter_name)
116
+ response = await waiter.wait(**params)
117
+
118
+ logger.debug('Response: %r', response)
data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/resources/base.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import warnings
3
+
4
+ from boto3.resources.base import ServiceResource
5
+
6
+ logger = logging.getLogger(__name__)
7
+
8
+
9
+ class AIOBoto3ServiceResource(ServiceResource):
10
+ async def __aenter__(self):
11
+ return self
12
+
13
+ async def __aexit__(self, exc_type, exc_val, exc_tb):
14
+ await self.meta.client.__aexit__(exc_type, exc_val, exc_tb)
15
+
16
+ def close(self):
17
+ warnings.warn("This should not be called anymore", DeprecationWarning)
18
+ return self.meta.client.close()
data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/resources/collection.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from typing import AsyncIterator, Any, cast
3
+
4
+ from boto3.docs import docstring
5
+ from boto3.resources.collection import CollectionFactory, ResourceCollection, CollectionManager, merge_dicts
6
+ from boto3.resources.params import create_request_parameters
7
+
8
+ from aioboto3.resources.action import AioBatchAction, AIOResourceHandler
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+
13
+ class AIOResourceCollection(ResourceCollection):
14
+ """
15
+ Converted the ResourceCollection.pages() function to an async generator so that we can do
16
+ async for on a paginator inside that function
17
+
18
+ Converted the __iter__
19
+ """
20
+ async def __anext__(self):
21
+ limit = self._params.get('limit', None)
22
+
23
+ count = 0
24
+ async for page in cast(AsyncIterator[Any], self.pages()):
25
+ for item in page:
26
+ yield item
27
+
28
+ count += 1
29
+ if limit is not None and count >= limit:
30
+ return
31
+
32
+ def __aiter__(self):
33
+ return self.__anext__()
34
+
35
+ def __iter__(self):
36
+ raise NotImplementedError('Use async-for instead')
37
+
38
+ async def pages(self):
39
+ client = self._parent.meta.client
40
+ cleaned_params = self._params.copy()
41
+ limit = cleaned_params.pop('limit', None)
42
+ page_size = cleaned_params.pop('page_size', None)
43
+ params = create_request_parameters(self._parent, self._model.request)
44
+ merge_dicts(params, cleaned_params, append_lists=True)
45
+
46
+ # Is this a paginated operation? If so, we need to get an
47
+ # iterator for the various pages. If not, then we simply
48
+ # call the operation and return the result as a single
49
+ # page in a list. For non-paginated results, we just ignore
50
+ # the page size parameter.
51
+ if client.can_paginate(self._py_operation_name):
52
+ logger.debug(
53
+ 'Calling paginated %s:%s with %r',
54
+ self._parent.meta.service_name,
55
+ self._py_operation_name,
56
+ params
57
+ )
58
+ paginator = client.get_paginator(self._py_operation_name)
59
+ pages = paginator.paginate(
60
+ PaginationConfig={'MaxItems': limit, 'PageSize': page_size},
61
+ **params
62
+ )
63
+ else:
64
+ async def _aiopaginatordummy():
65
+ yield await getattr(client, self._py_operation_name)(**params)
66
+
67
+ logger.debug(
68
+ 'Calling %s:%s with %r',
69
+ self._parent.meta.service_name,
70
+ self._py_operation_name,
71
+ params
72
+ )
73
+ pages = _aiopaginatordummy()
74
+
75
+ # Now that we have a page iterator or single page of results
76
+ # we start processing and yielding individual items.
77
+ count = 0
78
+ async for page in pages:
79
+ page_items = []
80
+ for item in await self._handler(self._parent, params, page):
81
+ page_items.append(item)
82
+
83
+ # If the limit is set and has been reached, then
84
+ # we stop processing items here.
85
+ count += 1
86
+ if limit is not None and count >= limit:
87
+ break
88
+
89
+ yield page_items
90
+
91
+ # Stop reading pages if we've reached out limit
92
+ if limit is not None and count >= limit:
93
+ break
94
+
95
+
96
+ class AIOCollectionManager(CollectionManager):
97
+ _collection_cls = AIOResourceCollection
98
+
99
+ def __init__(self, collection_model, parent, factory, service_context):
100
+ self._model = collection_model
101
+ operation_name = self._model.request.operation
102
+ self._parent = parent
103
+
104
+ search_path = collection_model.resource.path
105
+ self._handler = AIOResourceHandler(
106
+ search_path=search_path,
107
+ factory=factory,
108
+ resource_model=collection_model.resource,
109
+ service_context=service_context,
110
+ operation_name=operation_name
111
+ )
112
+
113
+
114
+ class AIOCollectionFactory(CollectionFactory):
115
+ def load_from_definition(
116
+ self, resource_name, collection_model, service_context, event_emitter
117
+ ):
118
+ attrs = {}
119
+ collection_name = collection_model.name
120
+
121
+ # Create the batch actions for a collection
122
+ self._load_batch_actions(
123
+ attrs,
124
+ resource_name,
125
+ collection_model,
126
+ service_context.service_model,
127
+ event_emitter
128
+ )
129
+ # Add the documentation to the collection class's methods
130
+ self._load_documented_collection_methods(
131
+ attrs=attrs,
132
+ resource_name=resource_name,
133
+ collection_model=collection_model,
134
+ service_model=service_context.service_model,
135
+ event_emitter=event_emitter,
136
+ base_class=AIOResourceCollection
137
+ )
138
+
139
+ if service_context.service_name == resource_name:
140
+ cls_name = (
141
+ f'{service_context.service_name}.{collection_name}Collection'
142
+ )
143
+ else:
144
+ cls_name = f'{service_context.service_name}.{resource_name}.{collection_name}Collection'
145
+
146
+ collection_cls = type(str(cls_name), (AIOResourceCollection,), attrs)
147
+
148
+ # Add the documentation to the collection manager's methods
149
+ self._load_documented_collection_methods(
150
+ attrs=attrs,
151
+ resource_name=resource_name,
152
+ collection_model=collection_model,
153
+ service_model=service_context.service_model,
154
+ event_emitter=event_emitter,
155
+ base_class=AIOCollectionManager
156
+ )
157
+ attrs['_collection_cls'] = collection_cls
158
+ cls_name += 'Manager'
159
+
160
+ return type(str(cls_name), (AIOCollectionManager,), attrs)
161
+
162
+ def _create_batch_action(
163
+ factory_self,
164
+ resource_name,
165
+ snake_cased,
166
+ action_model,
167
+ collection_model,
168
+ service_model,
169
+ event_emitter
170
+ ):
171
+ """
172
+ Creates a new method which makes a batch operation request
173
+ to the underlying service API.
174
+ """
175
+ action = AioBatchAction(action_model)
176
+
177
+ def batch_action(self, *args, **kwargs):
178
+ return action(self, *args, **kwargs)
179
+
180
+ batch_action.__name__ = str(snake_cased)
181
+ batch_action.__doc__ = docstring.BatchActionDocstring(
182
+ resource_name=resource_name,
183
+ event_emitter=event_emitter,
184
+ batch_action_model=action_model,
185
+ service_model=service_model,
186
+ collection_model=collection_model,
187
+ include_signature=False
188
+ )
189
+ return batch_action
data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/resources/factory.py ADDED
@@ -0,0 +1,289 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from functools import partial
3
+
4
+ from boto3.resources.factory import ResourceFactory
5
+ from boto3.resources.model import ResourceModel
6
+ from boto3.resources.base import ResourceMeta
7
+ from boto3.docs import docstring
8
+ from boto3.exceptions import ResourceLoadException
9
+ from boto3.resources.factory import build_identifiers
10
+
11
+ from aioboto3.resources.collection import AIOCollectionFactory
12
+ from aioboto3.resources.action import AIOServiceAction, AIOWaiterAction
13
+ from aioboto3.resources.base import AIOBoto3ServiceResource
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+
18
+ class AIOBoto3ResourceFactory(ResourceFactory):
19
+ # noinspection PyMissingConstructor
20
+ def __init__(self, emitter):
21
+ self._collection_factory = AIOCollectionFactory()
22
+ self._emitter = emitter
23
+
24
+ async def load_from_definition(self, resource_name,
25
+ single_resource_json_definition, service_context):
26
+ logger.debug('Loading %s:%s', service_context.service_name,
27
+ resource_name)
28
+
29
+ # Using the loaded JSON create a ResourceModel object.
30
+ resource_model = ResourceModel(
31
+ resource_name,
32
+ single_resource_json_definition,
33
+ service_context.resource_json_definitions
34
+ )
35
+
36
+ # Do some renaming of the shape if there was a naming collision
37
+ # that needed to be accounted for.
38
+ shape = None
39
+ if resource_model.shape:
40
+ shape = service_context.service_model.shape_for(
41
+ resource_model.shape
42
+ )
43
+ resource_model.load_rename_map(shape)
44
+
45
+ # Set some basic info
46
+ meta = ResourceMeta(
47
+ service_context.service_name, resource_model=resource_model)
48
+ attrs = {
49
+ 'meta': meta,
50
+ }
51
+
52
+ # Create and load all of attributes of the resource class based
53
+ # on the models.
54
+
55
+ # Identifiers
56
+ self._load_identifiers(
57
+ attrs=attrs,
58
+ meta=meta,
59
+ resource_name=resource_name,
60
+ resource_model=resource_model
61
+ )
62
+
63
+ # Load/Reload actions
64
+ self._load_actions(
65
+ attrs=attrs,
66
+ resource_name=resource_name,
67
+ resource_model=resource_model,
68
+ service_context=service_context
69
+ )
70
+
71
+ # Attributes that get auto-loaded
72
+ self._load_attributes(
73
+ attrs=attrs,
74
+ meta=meta,
75
+ resource_name=resource_name,
76
+ resource_model=resource_model,
77
+ service_context=service_context)
78
+
79
+ # Collections and their corresponding methods
80
+ self._load_collections(
81
+ attrs=attrs,
82
+ resource_model=resource_model,
83
+ service_context=service_context)
84
+
85
+ # References and Subresources
86
+ self._load_has_relations(
87
+ attrs=attrs,
88
+ resource_name=resource_name,
89
+ resource_model=resource_model,
90
+ service_context=service_context
91
+ )
92
+
93
+ # Waiter resource actions
94
+ self._load_waiters(
95
+ attrs=attrs,
96
+ resource_name=resource_name,
97
+ resource_model=resource_model,
98
+ service_context=service_context
99
+ )
100
+
101
+ # Create the name based on the requested service and resource
102
+ cls_name = resource_name
103
+ if service_context.service_name == resource_name:
104
+ cls_name = 'ServiceResource'
105
+ cls_name = service_context.service_name + '.' + cls_name
106
+
107
+ base_classes = [AIOBoto3ServiceResource]
108
+ if self._emitter is not None:
109
+ await self._emitter.emit(
110
+ 'creating-resource-class.%s' % cls_name,
111
+ class_attributes=attrs,
112
+ base_classes=base_classes,
113
+ service_context=service_context
114
+ )
115
+ return type(str(cls_name), tuple(base_classes), attrs)
116
+
117
+ def _create_autoload_property(
118
+ factory_self,
119
+ resource_name,
120
+ name,
121
+ snake_cased,
122
+ member_model,
123
+ service_context
124
+ ):
125
+ """
126
+ Creates a new property on the resource to lazy-load its value
127
+ via the resource's ``load`` method (if it exists).
128
+ """
129
+ # The property loader will check to see if this resource has already
130
+ # been loaded and return the cached value if possible. If not, then
131
+ # it first checks to see if it CAN be loaded (raise if not), then
132
+ # calls the load before returning the value.
133
+ async def property_loader(self):
134
+ if self.meta.data is None:
135
+ if hasattr(self, 'load'):
136
+ await self.load()
137
+ else:
138
+ raise ResourceLoadException(
139
+ '{0} has no load method'.format(
140
+ self.__class__.__name__))
141
+
142
+ return self.meta.data.get(name)
143
+
144
+ property_loader.__name__ = str(snake_cased)
145
+ property_loader.__doc__ = docstring.AttributeDocstring(
146
+ service_name=service_context.service_name,
147
+ resource_name=resource_name,
148
+ attr_name=snake_cased,
149
+ event_emitter=factory_self._emitter,
150
+ attr_model=member_model,
151
+ include_signature=False
152
+ )
153
+
154
+ return property(property_loader)
155
+
156
+ def _create_waiter(
157
+ factory_self, resource_waiter_model, resource_name, service_context
158
+ ):
159
+ """
160
+ Creates a new wait method for each resource where both a waiter and
161
+ resource model is defined.
162
+ """
163
+ waiter = AIOWaiterAction(
164
+ resource_waiter_model,
165
+ waiter_resource_name=resource_waiter_model.name
166
+ )
167
+
168
+ async def do_waiter(self, *args, **kwargs):
169
+ await waiter(self, *args, **kwargs)
170
+
171
+ do_waiter.__name__ = str(resource_waiter_model.name)
172
+ do_waiter.__doc__ = docstring.ResourceWaiterDocstring(
173
+ resource_name=resource_name,
174
+ event_emitter=factory_self._emitter,
175
+ service_model=service_context.service_model,
176
+ resource_waiter_model=resource_waiter_model,
177
+ service_waiter_model=service_context.service_waiter_model,
178
+ include_signature=False
179
+ )
180
+ return do_waiter
181
+
182
+ def _create_class_partial(
183
+ factory_self, subresource_model, resource_name, service_context
184
+ ):
185
+ """
186
+ Creates a new method which acts as a functools.partial, passing
187
+ along the instance's low-level `client` to the new resource
188
+ class' constructor.
189
+ """
190
+ name = subresource_model.resource.type
191
+
192
+ async def create_resource(self, *args, **kwargs):
193
+ # We need a new method here because we want access to the
194
+ # instance's client.
195
+ positional_args = []
196
+
197
+ # We lazy-load the class to handle circular references.
198
+ json_def = service_context.resource_json_definitions.get(name, {})
199
+ resource_cls = await factory_self.load_from_definition(
200
+ resource_name=name,
201
+ single_resource_json_definition=json_def,
202
+ service_context=service_context
203
+ )
204
+
205
+ # Assumes that identifiers are in order, which lets you do
206
+ # e.g. ``sqs.Queue('foo').Message('bar')`` to create a new message
207
+ # linked with the ``foo`` queue and which has a ``bar`` receipt
208
+ # handle. If we did kwargs here then future positional arguments
209
+ # would lead to failure.
210
+ identifiers = subresource_model.resource.identifiers
211
+ if identifiers is not None:
212
+ for identifier, value in build_identifiers(identifiers, self):
213
+ positional_args.append(value)
214
+
215
+ return partial(
216
+ resource_cls, *positional_args, client=self.meta.client
217
+ )(*args, **kwargs)
218
+
219
+ create_resource.__name__ = str(name)
220
+ create_resource.__doc__ = docstring.SubResourceDocstring(
221
+ resource_name=resource_name,
222
+ sub_resource_model=subresource_model,
223
+ service_model=service_context.service_model,
224
+ include_signature=False
225
+ )
226
+ return create_resource
227
+
228
+ def _create_action(
229
+ factory_self,
230
+ action_model,
231
+ resource_name,
232
+ service_context,
233
+ is_load=False
234
+ ):
235
+ """
236
+ Creates a new method which makes a request to the underlying
237
+ AWS service.
238
+ """
239
+ # Create the action in in this closure but before the ``do_action``
240
+ # method below is invoked, which allows instances of the resource
241
+ # to share the ServiceAction instance.
242
+ action = AIOServiceAction(
243
+ action_model, factory=factory_self, service_context=service_context
244
+ )
245
+
246
+ # A resource's ``load`` method is special because it sets
247
+ # values on the resource instead of returning the response.
248
+ if is_load:
249
+ # We need a new method here because we want access to the
250
+ # instance via ``self``.
251
+ async def do_action(self, *args, **kwargs):
252
+ response = await action(self, *args, **kwargs)
253
+ self.meta.data = response
254
+
255
+ # Create the docstring for the load/reload mehtods.
256
+ lazy_docstring = docstring.LoadReloadDocstring(
257
+ action_name=action_model.name,
258
+ resource_name=resource_name,
259
+ event_emitter=factory_self._emitter,
260
+ load_model=action_model,
261
+ service_model=service_context.service_model,
262
+ include_signature=False
263
+ )
264
+ else:
265
+ # We need a new method here because we want access to the
266
+ # instance via ``self``.
267
+ async def do_action(self, *args, **kwargs):
268
+ response = await action(self, *args, **kwargs)
269
+
270
+ if hasattr(self, 'load'):
271
+ # Clear cached data. It will be reloaded the next
272
+ # time that an attribute is accessed.
273
+ # TODO: Make this configurable in the future?
274
+ self.meta.data = None
275
+
276
+ return response
277
+
278
+ lazy_docstring = docstring.ActionDocstring(
279
+ resource_name=resource_name,
280
+ event_emitter=factory_self._emitter,
281
+ action_model=action_model,
282
+ service_model=service_context.service_model,
283
+ include_signature=False
284
+ )
285
+
286
+ do_action.__name__ = str(action_model.name)
287
+ do_action.__doc__ = lazy_docstring
288
+ return do_action
289
+
data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/resources/response.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from boto3.resources.response import RawHandler, ResourceHandler, build_identifiers, build_empty_response, all_not_none, jmespath
2
+
3
+
4
+ class AIOResourceHandler(ResourceHandler):
5
+ async def __call__(self, parent, params, response):
6
+ """
7
+ :type parent: ServiceResource
8
+ :param parent: The resource instance to which this action is attached.
9
+ :type params: dict
10
+ :param params: Request parameters sent to the service.
11
+ :type response: dict
12
+ :param response: Low-level operation response.
13
+ """
14
+ resource_name = self.resource_model.type
15
+ json_definition = self.service_context.resource_json_definitions.get(
16
+ resource_name
17
+ )
18
+
19
+ # Load the new resource class that will result from this action.
20
+ resource_cls = await self.factory.load_from_definition(
21
+ resource_name=resource_name,
22
+ single_resource_json_definition=json_definition,
23
+ service_context=self.service_context
24
+ )
25
+ raw_response = response
26
+ search_response = None
27
+
28
+ # Anytime a path is defined, it means the response contains the
29
+ # resource's attributes, so resource_data gets set here. It
30
+ # eventually ends up in resource.meta.data, which is where
31
+ # the attribute properties look for data.
32
+ if self.search_path:
33
+ search_response = jmespath.search(self.search_path, raw_response)
34
+
35
+ # First, we parse all the identifiers, then create the individual
36
+ # response resources using them. Any identifiers that are lists
37
+ # will have one item consumed from the front of the list for each
38
+ # resource that is instantiated. Items which are not a list will
39
+ # be set as the same value on each new resource instance.
40
+ identifiers = dict(
41
+ build_identifiers(
42
+ self.resource_model.identifiers, parent, params, raw_response
43
+ )
44
+ )
45
+
46
+ # If any of the identifiers is a list, then the response is plural
47
+ plural = [v for v in identifiers.values() if isinstance(v, list)]
48
+
49
+ if plural:
50
+ response = []
51
+
52
+ # The number of items in an identifier that is a list will
53
+ # determine how many resource instances to create.
54
+ for i in range(len(plural[0])):
55
+ # Response item data is *only* available if a search path
56
+ # was given. This prevents accidentally loading unrelated
57
+ # data that may be in the response.
58
+ response_item = None
59
+ if search_response:
60
+ response_item = search_response[i]
61
+ response.append(
62
+ self.handle_response_item(
63
+ resource_cls, parent, identifiers, response_item
64
+ )
65
+ )
66
+ elif all_not_none(identifiers.values()):
67
+ # All identifiers must always exist, otherwise the resource
68
+ # cannot be instantiated.
69
+ response = self.handle_response_item(
70
+ resource_cls, parent, identifiers, search_response
71
+ )
72
+ else:
73
+ # The response should be empty, but that may mean an
74
+ # empty dict, list, or None based on whether we make
75
+ # a remote service call and what shape it is expected
76
+ # to return.
77
+ response = None
78
+ if self.operation_name is not None:
79
+ # A remote service call was made, so try and determine
80
+ # its shape.
81
+ response = build_empty_response(
82
+ self.search_path,
83
+ self.operation_name,
84
+ self.service_context.service_model
85
+ )
86
+
87
+ return response
88
+
89
+
90
+ class AIORawHandler(RawHandler):
91
+ async def __call__(self, parent, params, response):
92
+ return super(AIORawHandler, self).__call__(parent, params, response)
data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/s3/__init__.py ADDED
File without changes
data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/s3/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (199 Bytes). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/s3/__pycache__/cse.cpython-311.pyc ADDED
Binary file (36 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/s3/__pycache__/inject.cpython-311.pyc ADDED
Binary file (33.3 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/s3/cse.py ADDED
@@ -0,0 +1,614 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import base64
3
+ import json
4
+ import inspect
5
+ import os
6
+ import re
7
+ import sys
8
+ import struct
9
+ from io import BytesIO
10
+ from typing import Dict, Union, IO, Optional, Any, Tuple
11
+
12
+ import aioboto3
13
+ from cryptography.hazmat.primitives.ciphers.aead import AESGCM
14
+ from cryptography.hazmat.backends import default_backend
15
+ from cryptography.hazmat.primitives.ciphers import Cipher
16
+ from cryptography.hazmat.primitives.ciphers.algorithms import AES
17
+ from cryptography.hazmat.primitives.ciphers.modes import CBC, CTR, ECB
18
+ from cryptography.hazmat.primitives.padding import PKCS7
19
+ from cryptography.exceptions import InvalidTag
20
+ from cryptography.hazmat.primitives.asymmetric import padding
21
+ from cryptography.hazmat.primitives.asymmetric.types import PrivateKeyTypes, PublicKeyTypes
22
+ from cryptography.hazmat.primitives import serialization
23
+
24
+
25
+ RANGE_REGEX = re.compile(r'bytes=(?P<start>\d+)-(?P<end>\d+)*')
26
+ AES_BLOCK_SIZE = 128
27
+ AES_BLOCK_SIZE_BYTES = 16
28
+ JAVA_LONG_MAX_VALUE = 9223372036854775807
29
+
30
+
31
+ # Just so it looks like the object aiohttp returns
32
+ class DummyAIOFile(object):
33
+ """So that response['Body'].read() presents the same way as a normal S3 get"""
34
+
35
+ def __init__(self, data: bytes):
36
+ self.file = BytesIO(data)
37
+
38
+ async def read(self, n=-1):
39
+ return self.file.read(n)
40
+
41
+ async def readany(self):
42
+ return self.file.read()
43
+
44
+ async def readexactly(self, n):
45
+ return self.file.read(n)
46
+
47
+ async def readchunk(self):
48
+ return self.file.read(), True
49
+
50
+
51
+ class DecryptError(Exception):
52
+ pass
53
+
54
+
55
+ class CryptoContext(object):
56
+ async def setup(self):
57
+ """
58
+ Coroutine to perform any setup
59
+ """
60
+ pass
61
+
62
+ async def close(self):
63
+ """
64
+ Coroutine to perform any teardown
65
+ """
66
+
67
+ async def get_decryption_aes_key(self, key: bytes, material_description: Dict[str, Any]) -> bytes:
68
+ """
69
+ Get decryption key for a given S3 object
70
+
71
+ :param key: Base64 decoded version of x-amz-key-v2
72
+ :param material_description: JSON decoded x-amz-matdesc
73
+ :return: Raw AES key bytes
74
+ """
75
+ raise NotImplementedError()
76
+
77
+ async def get_encryption_aes_key(self) -> Tuple[bytes, Dict[str, str], str]:
78
+ """
79
+ Get encryption key to encrypt an S3 object
80
+
81
+ :return: Raw AES key bytes, Stringified JSON x-amz-matdesc, Base64 encoded x-amz-key-v2
82
+ """
83
+ raise NotImplementedError()
84
+
85
+
86
+ class AsymmetricCryptoContext(CryptoContext):
87
+ """
88
+ Crypto context which uses public-private key cryptography.
89
+
90
+ The public and private keys need to be loaded in by ``cryptography.hazmat.primitives.serialization.*``
91
+
92
+ :param public_key: Public key object
93
+ :param private_key: Private key object
94
+ :param loop: Event loop
95
+ """
96
+
97
+ def __init__(self, public_key: Optional[PublicKeyTypes] = None,
98
+ private_key: Optional[PrivateKeyTypes] = None, loop: Optional[asyncio.AbstractEventLoop] = None):
99
+
100
+ self.public_key = public_key
101
+ self.private_key = private_key
102
+
103
+ self._loop = loop
104
+ if not loop:
105
+ self._loop = asyncio.get_event_loop()
106
+
107
+ async def get_decryption_aes_key(self, key: bytes, material_description: Dict[str, Any]) -> bytes:
108
+ """
109
+ Get decryption key for a given S3 object
110
+
111
+ :param key: Base64 decoded version of x-amz-key
112
+ :param material_description: JSON decoded x-amz-matdesc
113
+ :return: Raw AES key bytes
114
+ """
115
+ if self.private_key is None:
116
+ raise ValueError('Private key not provided during initialisation, cannot decrypt key encrypting key')
117
+
118
+ plaintext = await self._loop.run_in_executor(None, lambda: (self.private_key.decrypt(key, padding.PKCS1v15())))
119
+
120
+ return plaintext
121
+
122
+ async def get_encryption_aes_key(self) -> Tuple[bytes, Dict[str, str], str]:
123
+ """
124
+ Get encryption key to encrypt an S3 object
125
+
126
+ :return: Raw AES key bytes, Stringified JSON x-amz-matdesc, Base64 encoded x-amz-key
127
+ """
128
+ if self.public_key is None:
129
+ raise ValueError('Public key not provided during initialisation, cannot encrypt key encrypting key')
130
+
131
+ random_bytes = os.urandom(32)
132
+
133
+ ciphertext = await self._loop.run_in_executor(
134
+ None, lambda: (self.public_key.encrypt(random_bytes, padding.PKCS1v15())))
135
+
136
+ return random_bytes, {}, base64.b64encode(ciphertext).decode()
137
+
138
+ @staticmethod
139
+ def from_der_public_key(data: bytes) -> PublicKeyTypes:
140
+ """
141
+ Convert public key in DER encoding to a Public key object
142
+
143
+ :param data: public key bytes
144
+ """
145
+
146
+ return serialization.load_der_public_key(data, default_backend())
147
+
148
+ @staticmethod
149
+ def from_der_private_key(data: bytes, password: Optional[str] = None) -> PrivateKeyTypes:
150
+ """
151
+ Convert private key in DER encoding to a Private key object
152
+
153
+ :param data: private key bytes
154
+ :param password: password the private key is encrypted with
155
+ """
156
+ return serialization.load_der_private_key(data, password, default_backend())
157
+
158
+
159
+ class SymmetricCryptoContext(CryptoContext):
160
+ """
161
+ Crypto context which uses symmetric cryptography.
162
+
163
+ The key field should be a valid AES key.
164
+
165
+ :param key: Key bytes
166
+ :param loop: Event loop
167
+ """
168
+
169
+ def __init__(self, key: bytes, loop: Optional[asyncio.AbstractEventLoop] = None):
170
+ self.key = key
171
+ self._backend = default_backend()
172
+ self._cipher = Cipher(AES(self.key), ECB(), backend=self._backend)
173
+
174
+ self._loop = loop
175
+ if not loop:
176
+ self._loop = asyncio.get_event_loop()
177
+
178
+ async def get_decryption_aes_key(self, key: bytes, material_description: Dict[str, Any]) -> bytes:
179
+ """
180
+ Get decryption key for a given S3 object
181
+
182
+ :param key: Base64 decoded version of x-amz-key
183
+ :param material_description: JSON decoded x-amz-matdesc
184
+ :return: Raw AES key bytes
185
+ """
186
+
187
+ # So it seems when java just calls Cipher.getInstance('AES') it'll default to AES/ECB/PKCS5Padding
188
+ aesecb = self._cipher.decryptor()
189
+ padded_result = await self._loop.run_in_executor(None, lambda: (aesecb.update(key) + aesecb.finalize()))
190
+
191
+ unpadder = PKCS7(AES.block_size).unpadder()
192
+ result = await self._loop.run_in_executor(None, lambda: (unpadder.update(padded_result) + unpadder.finalize()))
193
+
194
+ return result
195
+
196
+ async def get_encryption_aes_key(self) -> Tuple[bytes, Dict[str, str], str]:
197
+ """
198
+ Get encryption key to encrypt an S3 object
199
+
200
+ :return: Raw AES key bytes, Stringified JSON x-amz-matdesc, Base64 encoded x-amz-key
201
+ """
202
+
203
+ random_bytes = os.urandom(32)
204
+
205
+ padder = PKCS7(AES.block_size).padder()
206
+ padded_result = await self._loop.run_in_executor(
207
+ None, lambda: (padder.update(random_bytes) + padder.finalize()))
208
+
209
+ aesecb = self._cipher.encryptor()
210
+ encrypted_result = await self._loop.run_in_executor(
211
+ None, lambda: (aesecb.update(padded_result) + aesecb.finalize()))
212
+
213
+ return random_bytes, {}, base64.b64encode(encrypted_result).decode()
214
+
215
+
216
+ class KMSCryptoContext(CryptoContext):
217
+ """
218
+ Crypto context which uses symmetric cryptography.
219
+
220
+ The key field should be a valid AES key.
221
+
222
+ E.g. if you wanted to set the KMS region, add kms_client_args={'region_name': 'eu-west-1'}
223
+
224
+ :param key: Key bytes
225
+ :param kms_client_args: Will be expanded when getting a KMS client
226
+ :param authenticated_encryption: Uses AES-GCM instead of AES-CBC (also allows range gets of files)
227
+ :param loop: Event loop
228
+ """
229
+
230
+ def __init__(self, keyid: Optional[str] = None, kms_client_args: Optional[dict] = None,
231
+ authenticated_encryption: bool = True):
232
+ self.kms_key = keyid
233
+ self.authenticated_encryption = authenticated_encryption
234
+
235
+ # Store the client instead of creating one every time, performance wins when doing many files
236
+ self._kms_client = None
237
+ self._kms_client_args = kms_client_args if kms_client_args else {}
238
+ self._session = None
239
+
240
+ async def setup(self):
241
+ self._session = aioboto3.Session()
242
+ self._kms_client = await self._session.client('kms', **self._kms_client_args).__aenter__()
243
+
244
+ async def close(self):
245
+ await self._kms_client.close()
246
+
247
+ async def get_decryption_aes_key(self, key: bytes, material_description: Dict[str, Any]) -> bytes:
248
+ kms_data = await self._kms_client.decrypt(
249
+ CiphertextBlob=key,
250
+ EncryptionContext=material_description
251
+ )
252
+ return kms_data['Plaintext']
253
+
254
+ async def get_encryption_aes_key(self) -> Tuple[bytes, Dict[str, str], str]:
255
+ if self.kms_key is None:
256
+ raise ValueError('KMS Key not provided during initalisation, cannot decrypt key encrypting key')
257
+
258
+ encryption_context = {'kms_cmk_id': self.kms_key}
259
+ kms_resp = await self._kms_client.generate_data_key(
260
+ KeyId=self.kms_key,
261
+ EncryptionContext=encryption_context,
262
+ KeySpec='AES_256'
263
+ )
264
+
265
+ return kms_resp['Plaintext'], encryption_context, base64.b64encode(kms_resp['CiphertextBlob']).decode()
266
+
267
+
268
+ class MockKMSCryptoContext(KMSCryptoContext):
269
+ def __init__(self, aes_key: bytes, material_description: dict, encrypted_key: bytes,
270
+ authenticated_encryption: bool = True):
271
+ super(MockKMSCryptoContext, self).__init__()
272
+ self.aes_key = aes_key
273
+ self.material_description = material_description
274
+ self.encrypted_key = encrypted_key
275
+ self.authenticated_encryption = authenticated_encryption
276
+
277
+ async def setup(self):
278
+ pass
279
+
280
+ async def close(self):
281
+ pass
282
+
283
+ async def get_decryption_aes_key(self, key: bytes, material_description: Dict[str, Any]) -> bytes:
284
+ return self.aes_key
285
+
286
+ async def get_encryption_aes_key(self) -> Tuple[bytes, Dict[str, str], str]:
287
+ return self.aes_key, self.material_description.copy(), base64.b64encode(self.encrypted_key).decode()
288
+
289
+
290
+ class S3CSE(object):
291
+ """
292
+ S3 Client-side encryption wrapper.
293
+
294
+ To change S3 region add s3_client_args={'region_name': 'eu-west-1'}
295
+
296
+ To use this object, either use it with ``async with S3CSE(...) as s3_cse:``
297
+ Or run the setup() and close() coro's respectively
298
+
299
+ :param crypto_context: Takes a cryto context object from above
300
+ :param s3_client_args: Optional dict of S3 client args
301
+ """
302
+
303
+ def __init__(self, crypto_context: CryptoContext, s3_client_args: Optional[dict] = None):
304
+ self._loop = None
305
+ self._backend = default_backend()
306
+
307
+ self._crypto_context = crypto_context
308
+ self._session = None
309
+ self._s3_client = None
310
+ self._s3_client_args = s3_client_args if s3_client_args else {}
311
+
312
+ async def setup(self):
313
+ if sys.version_info < (3, 7):
314
+ self._loop = asyncio.get_event_loop()
315
+ else:
316
+ self._loop = asyncio.get_running_loop()
317
+
318
+ self._session = aioboto3.Session()
319
+ self._s3_client = await self._session.client('s3', **self._s3_client_args).__aenter__()
320
+ await self._crypto_context.setup()
321
+
322
+ async def close(self):
323
+ await self._s3_client.close()
324
+ await self._crypto_context.close()
325
+
326
+ async def __aenter__(self):
327
+ await self.setup()
328
+ return self
329
+
330
+ async def __aexit__(self, exc_type, exc_val, exc_tb):
331
+ await self.close()
332
+
333
+ # noinspection PyPep8Naming
334
+ async def get_object(self, Bucket: str, Key: str, **kwargs) -> dict:
335
+ """
336
+ S3 GetObject. Takes same args as Boto3 documentation
337
+
338
+ Decrypts any CSE
339
+
340
+ :param Bucket: S3 Bucket
341
+ :param Key: S3 Key (filepath)
342
+ :return: returns same response as a normal S3 get_object
343
+ """
344
+ if self._s3_client is None:
345
+ await self.setup()
346
+
347
+ # Ok so if we are doing a range get. We need to align the range start/end with AES block boundaries
348
+ # 9223372036854775806 is 8EiB so I have no issue with hardcoding it.
349
+ # We pass the actual start, desired start and desired end to the decrypt function so that it can
350
+ # generate the correct IV's for starting decryption at that block and then chop off the start and end of the
351
+ # AES block so it matches what the user is expecting.
352
+ _range = kwargs.get('Range')
353
+ actual_range_start = None
354
+ desired_range_start = None
355
+ desired_range_end = None
356
+ if _range:
357
+ range_match = RANGE_REGEX.match(_range)
358
+ if not range_match:
359
+ raise ValueError('Dont understand this range value {0}'.format(_range))
360
+
361
+ desired_range_start = int(range_match.group(1))
362
+ desired_range_end = range_match.group(2)
363
+ if desired_range_end is None:
364
+ desired_range_end = 9223372036854775806
365
+ else:
366
+ desired_range_end = int(desired_range_end)
367
+
368
+ actual_range_start, actual_range_end = _get_adjusted_crypto_range(desired_range_start, desired_range_end)
369
+
370
+ # Update range with actual start_end
371
+ kwargs['Range'] = 'bytes={0}-{1}'.format(actual_range_start, actual_range_end)
372
+
373
+ s3_response = await self._s3_client.get_object(Bucket=Bucket, Key=Key, **kwargs)
374
+ metadata = s3_response['Metadata']
375
+ whole_file_length = int(s3_response['ResponseMetadata']['HTTPHeaders']['content-length'])
376
+
377
+ if 'x-amz-key' not in metadata and 'x-amz-key-v2' not in metadata:
378
+ # No crypto
379
+ return s3_response
380
+
381
+ if 'x-amz-key' in metadata:
382
+ # Crypto V1
383
+ # Todo move the file obj into the decrypt to do streaming
384
+ file_data = await s3_response['Body'].read()
385
+ body = await self._decrypt_v1(file_data, metadata, actual_range_start)
386
+ else:
387
+ # Crypto V2
388
+ # Todo move the file obj into the decrypt to do streaming
389
+ file_data = await s3_response['Body'].read()
390
+ body = await self._decrypt_v2(file_data, metadata, whole_file_length,
391
+ actual_range_start, desired_range_start,
392
+ desired_range_end)
393
+
394
+ s3_response['Body'] = DummyAIOFile(body)
395
+
396
+ return s3_response
397
+
398
+ async def _decrypt_v1(self, file_data: bytes, metadata: Dict[str, str], range_start: Optional[int] = None) -> bytes:
399
+ if range_start:
400
+ raise DecryptError('Cant do range get when not using KMS encryption')
401
+
402
+ decryption_key = base64.b64decode(metadata['x-amz-key'])
403
+ material_description = json.loads(metadata['x-amz-matdesc'])
404
+
405
+ aes_key = await self._crypto_context.get_decryption_aes_key(decryption_key, material_description)
406
+
407
+ # x-amz-key - Contains base64 encrypted key
408
+ # x-amz-iv - AES IVs
409
+ # x-amz-matdesc - JSON Description of client-side master key (used as encryption context as is)
410
+ # x-amz-unencrypted-content-length - Unencrypted content length
411
+
412
+ iv = base64.b64decode(metadata['x-amz-iv'])
413
+
414
+ # TODO look at doing AES as stream
415
+
416
+ # AES/CBC/PKCS5Padding
417
+ aescbc = Cipher(AES(aes_key), CBC(iv), backend=self._backend).decryptor()
418
+ padded_result = await self._loop.run_in_executor(None, lambda: (aescbc.update(file_data) + aescbc.finalize()))
419
+
420
+ unpadder = PKCS7(AES.block_size).unpadder()
421
+ result = await self._loop.run_in_executor(None, lambda: (unpadder.update(padded_result) + unpadder.finalize()))
422
+
423
+ return result
424
+
425
+ async def _decrypt_v2(self, file_data: bytes, metadata: Dict[str, str], entire_file_length: int,
426
+ range_start: Optional[int] = None, desired_start: Optional[int] = None,
427
+ desired_end: Optional[int] = None) -> bytes:
428
+
429
+ decryption_key = base64.b64decode(metadata['x-amz-key-v2'])
430
+ material_description = json.loads(metadata['x-amz-matdesc'])
431
+
432
+ aes_key = await self._crypto_context.get_decryption_aes_key(decryption_key, material_description)
433
+
434
+ # x-amz-key-v2 - Contains base64 encrypted key
435
+ # x-amz-iv - AES IVs
436
+ # x-amz-matdesc - JSON Description of client-side master key (used as encryption context as is)
437
+ # x-amz-unencrypted-content-length - Unencrypted content length
438
+ # x-amz-wrap-alg - Key wrapping algo, either AESWrap, RSA/ECB/OAEPWithSHA-256AndMGF1Padding or KMS
439
+ # x-amz-cek-alg - AES/GCM/NoPadding or AES/CBC/PKCS5Padding
440
+ # x-amz-tag-len - AEAD Tag length in bits
441
+
442
+ iv = base64.b64decode(metadata['x-amz-iv'])
443
+
444
+ # TODO look at doing AES as stream
445
+ if metadata.get('x-amz-cek-alg', 'AES/CBC/PKCS5Padding') == 'AES/GCM/NoPadding':
446
+ # AES/GCM/NoPadding
447
+
448
+ # So begin the nastyness
449
+ if range_start is not None:
450
+ # Generate IV's as if you were doing so for each block until we get to the one we need
451
+ iv = _adjust_iv_for_range(iv, range_start)
452
+ # IV is now 16 bytes not 12
453
+
454
+ aesctr = Cipher(AES(aes_key), CTR(iv), backend=self._backend).decryptor()
455
+
456
+ result = await self._loop.run_in_executor(None, lambda: (aesctr.update(file_data) + aesctr.finalize()))
457
+
458
+ # Possible remove AEAD tag if our range covers the end
459
+ aead_tag_len = int(metadata['x-amz-tag-len']) // 8
460
+ max_offset = entire_file_length - aead_tag_len - 1
461
+ desired_end = max_offset if desired_end > max_offset else desired_end
462
+
463
+ # Chop file
464
+ result = result[desired_start:desired_end]
465
+
466
+ else:
467
+ aesgcm = AESGCM(aes_key)
468
+
469
+ try:
470
+ result = await self._loop.run_in_executor(None, lambda: aesgcm.decrypt(iv, file_data, None))
471
+ except InvalidTag:
472
+ raise DecryptError('Failed to decrypt, AEAD tag is incorrect. Possible key or IV are incorrect')
473
+
474
+ else:
475
+ if range_start:
476
+ raise DecryptError('Cannot decrypt AES-CBC file with range')
477
+
478
+ # AES/CBC/PKCS5Padding
479
+ aescbc = Cipher(AES(aes_key), CBC(iv), backend=self._backend).decryptor()
480
+ padded_result = await self._loop.run_in_executor(
481
+ None, lambda: (aescbc.update(file_data) + aescbc.finalize()))
482
+
483
+ unpadder = PKCS7(AES.block_size).unpadder()
484
+ result = await self._loop.run_in_executor(
485
+ None, lambda: (unpadder.update(padded_result) + unpadder.finalize()))
486
+
487
+ return result
488
+
489
+ async def put_object(self, Body: Union[bytes, IO], Bucket: str, Key: str, Metadata: Dict = None, **kwargs):
490
+ """
491
+ PutObject. Takes same args as Boto3 documentation
492
+
493
+ Encrypts files
494
+
495
+ :param: Body: File data
496
+ :param Bucket: S3 Bucket
497
+ :param Key: S3 Key (filepath)
498
+ """
499
+ if self._s3_client is None:
500
+ await self.setup()
501
+
502
+ if hasattr(Body, 'read'):
503
+ if inspect.iscoroutinefunction(Body.read):
504
+ Body = await Body.read()
505
+ else:
506
+ Body = Body.read()
507
+
508
+ # We do some different V2 stuff if using kms
509
+ is_kms = isinstance(self._crypto_context, KMSCryptoContext)
510
+ # noinspection PyUnresolvedReferences
511
+ authenticated_crypto = is_kms and self._crypto_context.authenticated_encryption
512
+
513
+ Metadata = Metadata if Metadata is not None else {}
514
+
515
+ aes_key, matdesc_metadata, key_metadata = await self._crypto_context.get_encryption_aes_key()
516
+
517
+ if is_kms and authenticated_crypto:
518
+ Metadata['x-amz-cek-alg'] = 'AES/GCM/NoPadding'
519
+ Metadata['x-amz-tag-len'] = str(AES_BLOCK_SIZE)
520
+ iv = os.urandom(12)
521
+
522
+ # 16byte 128bit authentication tag forced
523
+ aesgcm = AESGCM(aes_key)
524
+
525
+ result = await self._loop.run_in_executor(None, lambda: aesgcm.encrypt(iv, Body, None))
526
+
527
+ else:
528
+ if is_kms: # V1 is always AES/CBC/PKCS5Padding
529
+ Metadata['x-amz-cek-alg'] = 'AES/CBC/PKCS5Padding'
530
+
531
+ iv = os.urandom(16)
532
+
533
+ padder = PKCS7(AES.block_size).padder()
534
+ padded_result = await self._loop.run_in_executor(None, lambda: (padder.update(Body) + padder.finalize()))
535
+
536
+ aescbc = Cipher(AES(aes_key), CBC(iv), backend=self._backend).encryptor()
537
+ result = await self._loop.run_in_executor(None, lambda: (aescbc.update(padded_result) + aescbc.finalize()))
538
+
539
+ # For all V1 and V2
540
+ Metadata['x-amz-unencrypted-content-length'] = str(len(Body))
541
+ Metadata['x-amz-iv'] = base64.b64encode(iv).decode()
542
+ Metadata['x-amz-matdesc'] = json.dumps(matdesc_metadata)
543
+
544
+ if is_kms:
545
+ Metadata['x-amz-wrap-alg'] = 'kms'
546
+ Metadata['x-amz-key-v2'] = key_metadata
547
+ else:
548
+ Metadata['x-amz-key'] = key_metadata
549
+
550
+ await self._s3_client.put_object(
551
+ Bucket=Bucket,
552
+ Key=Key,
553
+ Body=result,
554
+ Metadata=Metadata,
555
+ **kwargs
556
+ )
557
+
558
+
559
+ def _adjust_iv_for_range(iv: bytes, byte_offset: int) -> bytes:
560
+ if len(iv) != 12:
561
+ raise RuntimeError('IV must be 12 bytes long for AES-GCM/CTR')
562
+
563
+ block_size = AES_BLOCK_SIZE
564
+ block_offset = byte_offset // block_size
565
+ if block_offset * block_size != byte_offset:
566
+ raise RuntimeError('Range size invalid. Should never hit this as range should be adjusted by now')
567
+
568
+ j0 = _compute_j0(iv)
569
+ return _increment_blocks(j0, block_offset)
570
+
571
+
572
+ def _get_adjusted_crypto_range(start: int, end: int) -> Tuple[int, int]:
573
+ start = _get_cipher_block_lower_bound(start)
574
+ end = _get_cipher_block_upper_bound(end) # Copied from teh JAVA
575
+
576
+ return start, end
577
+
578
+
579
+ def _get_cipher_block_lower_bound(value: int) -> int:
580
+ lower_bound = value - (value % AES_BLOCK_SIZE) - AES_BLOCK_SIZE
581
+ return max(lower_bound, 0)
582
+
583
+
584
+ def _get_cipher_block_upper_bound(value: int) -> int:
585
+ offset = AES_BLOCK_SIZE - (value % AES_BLOCK_SIZE)
586
+ upper_bound = value + offset + AES_BLOCK_SIZE
587
+ return min(upper_bound, JAVA_LONG_MAX_VALUE)
588
+
589
+
590
+ def _compute_j0(iv: bytes) -> bytes:
591
+ j0 = iv + (b'\x00' * (AES_BLOCK_SIZE_BYTES - 13)) + b'\x01' # iv must be of length 12
592
+
593
+ return _increment_blocks(j0, 1)
594
+
595
+
596
+ def _increment_blocks(counter: bytes, block_delta: int) -> bytes:
597
+ if block_delta == 0:
598
+ return counter
599
+
600
+ if not counter or len(counter) != 16:
601
+ raise ValueError('Counter must be 16 bytes long')
602
+
603
+ byte_buffer = [0] * 8
604
+
605
+ i = 12
606
+ while i <= 15:
607
+ byte_buffer[i-8] = counter[i]
608
+ i += 1
609
+
610
+ result = struct.pack('>Q', struct.unpack('>Q', bytes(byte_buffer))[0] + block_delta)
611
+
612
+ counter = counter[:12] + result[4:8]
613
+
614
+ return counter
data/conda_envs/evalclaw/lib/python3.11/site-packages/aioboto3/s3/inject.py ADDED
@@ -0,0 +1,732 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import aiofiles
3
+ import inspect
4
+ import logging
5
+ import math
6
+ from functools import partial
7
+ from io import BytesIO
8
+ from typing import Optional, Callable, BinaryIO, Dict, Any, Union
9
+ from abc import abstractmethod
10
+
11
+ from aiobotocore.context import with_current_context
12
+ from botocore.exceptions import ClientError
13
+ from botocore.useragent import register_feature_id
14
+ from boto3 import utils
15
+ from boto3.s3.transfer import S3TransferConfig, S3Transfer
16
+ from boto3.s3.inject import bucket_upload_file, bucket_download_file, bucket_copy, bucket_upload_fileobj, bucket_download_fileobj
17
+ from s3transfer.upload import UploadSubmissionTask
18
+ from s3transfer.copies import CopySubmissionTask
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+
23
+ TransferCallback = Callable[[int], None]
24
+
25
+
26
+ class _AsyncBinaryIO:
27
+ @abstractmethod
28
+ async def seek(self, offset: int, whence: int = 0) -> int:
29
+ pass
30
+
31
+ @abstractmethod
32
+ async def write(self, s: Union[bytes, bytearray]) -> int:
33
+ pass
34
+
35
+
36
+ AnyFileObject = Union[_AsyncBinaryIO, BinaryIO]
37
+
38
+
39
+ def inject_s3_transfer_methods(class_attributes, **kwargs):
40
+ utils.inject_attribute(class_attributes, 'upload_file', upload_file)
41
+ utils.inject_attribute(class_attributes, 'download_file', download_file)
42
+ utils.inject_attribute(class_attributes, 'copy', copy)
43
+ utils.inject_attribute(class_attributes, 'upload_fileobj', upload_fileobj)
44
+ utils.inject_attribute(
45
+ class_attributes, 'download_fileobj', download_fileobj
46
+ )
47
+
48
+
49
+ def inject_object_summary_methods(class_attributes, **kwargs):
50
+ utils.inject_attribute(class_attributes, 'load', object_summary_load)
51
+
52
+
53
+ def inject_bucket_methods(class_attributes, **kwargs):
54
+ utils.inject_attribute(class_attributes, 'load', bucket_load)
55
+ utils.inject_attribute(class_attributes, 'upload_file', bucket_upload_file)
56
+ utils.inject_attribute(
57
+ class_attributes, 'download_file', bucket_download_file
58
+ )
59
+ utils.inject_attribute(class_attributes, 'copy', bucket_copy)
60
+ utils.inject_attribute(
61
+ class_attributes, 'upload_fileobj', bucket_upload_fileobj
62
+ )
63
+ utils.inject_attribute(
64
+ class_attributes, 'download_fileobj', bucket_download_fileobj
65
+ )
66
+
67
+
68
+ async def object_summary_load(self, *args, **kwargs):
69
+ response = await self.meta.client.head_object(
70
+ Bucket=self.bucket_name, Key=self.key
71
+ )
72
+ if 'ContentLength' in response:
73
+ response['Size'] = response.pop('ContentLength')
74
+ self.meta.data = response
75
+
76
+
77
+ @with_current_context(partial(register_feature_id, 'S3_TRANSFER'))
78
+ async def download_file(
79
+ self,
80
+ Bucket: str,
81
+ Key: str,
82
+ Filename: str,
83
+ ExtraArgs: Optional[Dict[str, Any]] = None,
84
+ Callback: Optional[TransferCallback] = None,
85
+ Config: Optional[S3TransferConfig] = None
86
+ ):
87
+ """Download an S3 object to a file asynchronously.
88
+
89
+ Usage::
90
+
91
+ import aioboto3
92
+
93
+ async with aioboto3.resource('s3') as s3:
94
+ await s3.meta.client.download_file('mybucket', 'hello.txt', '/tmp/hello.txt')
95
+
96
+ Similar behaviour as S3Transfer's download_file() method,
97
+ except that parameters are capitalised.
98
+ """
99
+ async with aiofiles.open(Filename, 'wb') as fileobj: # type: _AsyncBinaryIO
100
+ await download_fileobj(
101
+ self,
102
+ Bucket,
103
+ Key,
104
+ fileobj,
105
+ ExtraArgs=ExtraArgs,
106
+ Callback=Callback,
107
+ Config=Config
108
+ )
109
+
110
+
111
+ async def _download_part(self, bucket: str, key: str, extraArgs: Dict[str, str], headers: Dict[str, str], start: int, file: AnyFileObject, semaphore: asyncio.Semaphore, write_lock: asyncio.Lock,
112
+ callback=None, io_queue: Optional[asyncio.Queue] = None) -> None:
113
+ async with semaphore: # limit number of concurrent downloads
114
+ response = await self.get_object(
115
+ Bucket=bucket, Key=key, Range=headers['Range'], **extraArgs
116
+ )
117
+ content = await response['Body'].read()
118
+
119
+ # If stream is not seekable, return the offset and data so it can be queued up to be written
120
+ if io_queue:
121
+ await io_queue.put((start, content))
122
+ else:
123
+ # Check if it's aiofiles file
124
+ if inspect.iscoroutinefunction(file.seek) and inspect.iscoroutinefunction(file.write):
125
+ # These operations need to happen sequentially, which is non-deterministic when dealing with event loops
126
+ async with write_lock:
127
+ await file.seek(start)
128
+ await file.write(content)
129
+ else:
130
+ # Fallback to synchronous operations for file objects that are not async
131
+ file.seek(start)
132
+ file.write(content)
133
+
134
+ # Call the wrapper callback with the number of bytes written, if provided
135
+ if callback:
136
+ try:
137
+ callback(len(content))
138
+ except: # noqa: E722
139
+ pass
140
+
141
+
142
+ @with_current_context(partial(register_feature_id, 'S3_TRANSFER'))
143
+ async def download_fileobj(
144
+ self,
145
+ Bucket: str,
146
+ Key: str,
147
+ Fileobj: AnyFileObject,
148
+ ExtraArgs: Optional[Dict[str, Any]] = None,
149
+ Callback: Optional[TransferCallback] = None,
150
+ Config: Optional[S3TransferConfig] = None
151
+ ):
152
+ """Download an object from S3 to a file-like object.
153
+
154
+ The file-like object must be in binary mode.
155
+
156
+ This is a managed transfer which will perform a multipart download
157
+ with asyncio if necessary.
158
+
159
+ Usage::
160
+
161
+ import aioboto3
162
+ s3 = aioboto3.client('s3')
163
+
164
+ async with aiofiles.open('filename', 'wb') as data:
165
+ await s3.download_fileobj('mybucket', 'mykey', data)
166
+
167
+ :type Fileobj: a file-like object
168
+ :param Fileobj: A file-like object to download into. At a minimum, it must
169
+ implement the `write` method and must accept bytes.
170
+
171
+ :type Bucket: str
172
+ :param Bucket: The name of the bucket to download from.
173
+
174
+ :type Key: str
175
+ :param Key: The name of the key to download from.
176
+
177
+ :type ExtraArgs: dict
178
+ :param ExtraArgs: Extra arguments that may be passed to the
179
+ client operation.
180
+
181
+ :type Callback: method
182
+ :param Callback: A method which takes a number of bytes transferred to
183
+ be periodically called during the download.
184
+
185
+ :type Config: boto3.s3.transfer.TransferConfig
186
+ :param Config: The transfer configuration to be used when performing the
187
+ download.
188
+ """
189
+
190
+ Config = Config or S3TransferConfig()
191
+ ExtraArgs = ExtraArgs or {}
192
+
193
+ try:
194
+ # Get object metadata to determine the total size
195
+ head_response = await self.head_object(Bucket=Bucket, Key=Key, **ExtraArgs)
196
+ except ClientError as err:
197
+ if err.response['Error']['Code'] == 'NoSuchKey':
198
+ # Convert to 404 so it looks the same when boto3.download_file fails
199
+ raise ClientError({'Error': {'Code': '404', 'Message': 'Not Found'}}, 'HeadObject')
200
+ raise
201
+
202
+ # Semaphore to limit the number of concurrent downloads
203
+ semaphore = asyncio.Semaphore(Config.max_request_concurrency)
204
+ write_mutex = asyncio.Lock()
205
+
206
+ total_size = head_response['ContentLength']
207
+ total_parts = (total_size + Config.multipart_chunksize - 1) // Config.multipart_chunksize
208
+
209
+ # Keep track of total downloaded bytes
210
+ total_downloaded = 0
211
+
212
+ def wrapper_callback(bytes_transferred):
213
+ nonlocal total_downloaded
214
+ total_downloaded += bytes_transferred
215
+ if Callback:
216
+ try:
217
+ Callback(total_downloaded)
218
+ except: # noqa: E722
219
+ pass
220
+
221
+ is_seekable = hasattr(Fileobj, "seek")
222
+
223
+ # This'll have around `semaphore` length items, somewhat more if writing is slow
224
+ # TODO add limits so we dont fill up this list n blow out ram
225
+ io_list = []
226
+
227
+ # This should be Config.io_concurrency but as we're gathering all coro's we cant guarantee
228
+ # that the co-routines will start in relative order so we could fill up the queue with the
229
+ # x chunks and if we're not writing to a seekable stream then it'll deadlock.
230
+ io_queue = asyncio.Queue()
231
+
232
+ async def queue_reader():
233
+ """
234
+ Pretty much, get things off queue, add them to list
235
+ Go through list, write things to file object in order
236
+ """
237
+ is_async = inspect.iscoroutinefunction(Fileobj.write)
238
+
239
+ try:
240
+ written_pos = 0
241
+ while written_pos < total_size:
242
+ io_list.append(await io_queue.get())
243
+
244
+ # Stuff might be out of order in io_list
245
+ # so spin until there's nothing to queue off
246
+ done_nothing = False
247
+ while not done_nothing:
248
+ done_nothing = True
249
+
250
+ indexes_to_remove = []
251
+ for index, (chunk_start, data) in enumerate(io_list):
252
+ if chunk_start == written_pos:
253
+ if is_async:
254
+ await Fileobj.write(data)
255
+ else:
256
+ Fileobj.write(data)
257
+
258
+ indexes_to_remove.append(index)
259
+ written_pos += len(data)
260
+ done_nothing = False
261
+
262
+ for index in reversed(indexes_to_remove):
263
+ io_list.pop(index)
264
+ except asyncio.CancelledError:
265
+ pass
266
+
267
+ queue_reader_future = None
268
+ if not is_seekable:
269
+ queue_reader_future = asyncio.ensure_future(queue_reader())
270
+
271
+ try:
272
+ tasks = []
273
+ for i in range(total_parts):
274
+ start = i * Config.multipart_chunksize
275
+ end = min(
276
+ start + Config.multipart_chunksize, total_size
277
+ ) # Ensure we don't go beyond the total size
278
+ # Range headers, start at 0 so end which would be total_size, minus 1 = 0 indexed.
279
+ headers = {'Range': f'bytes={start}-{end - 1}'}
280
+ # Create a task for each part download
281
+ tasks.append(
282
+ _download_part(self, Bucket, Key, ExtraArgs, headers, start, Fileobj, semaphore, write_mutex, wrapper_callback, io_queue if not is_seekable else None)
283
+ )
284
+
285
+ # Run all the download tasks concurrently
286
+ await asyncio.gather(*tasks) # TODO might not be worth spamming the eventloop with 1000's of tasks, but deal with it when its a problem.
287
+
288
+ if queue_reader_future:
289
+ await queue_reader_future
290
+
291
+ logger.debug(f'Downloaded file from {Bucket}/{Key}')
292
+
293
+ except ClientError as e:
294
+ raise Exception(
295
+ f"Couldn't download file from {Bucket}/{Key}"
296
+ ) from e
297
+
298
+
299
+ @with_current_context(partial(register_feature_id, 'S3_TRANSFER'))
300
+ async def upload_fileobj(
301
+ self,
302
+ Fileobj: AnyFileObject,
303
+ Bucket: str,
304
+ Key: str,
305
+ ExtraArgs: Optional[Dict[str, Any]] = None,
306
+ Callback: Optional[TransferCallback] = None,
307
+ Config: Optional[S3TransferConfig] = None,
308
+ Processing: Callable[[bytes], bytes] = None
309
+ ):
310
+ """Upload a file-like object to S3.
311
+
312
+ The file-like object must be in binary mode.
313
+
314
+ This is a managed transfer which will perform a multipart upload in
315
+ multiple threads if necessary.
316
+
317
+ Usage::
318
+
319
+ import aioboto3
320
+ s3 = aioboto3.client('s3')
321
+
322
+ async with aiofiles.open('filename', 'rb') as data:
323
+ await s3.upload_fileobj(data, 'mybucket', 'mykey')
324
+
325
+ :type Fileobj: a file-like object
326
+ :param Fileobj: A file-like object to upload. At a minimum, it must
327
+ implement the `read` method, and must return bytes.
328
+
329
+ :type Bucket: str
330
+ :param Bucket: The name of the bucket to upload to.
331
+
332
+ :type Key: str
333
+ :param Key: The name of the key to upload to.
334
+
335
+ :type ExtraArgs: dict
336
+ :param ExtraArgs: Extra arguments that may be passed to the
337
+ client operation.
338
+
339
+ :type Callback: method
340
+ :param Callback: A method which takes a number of bytes transferred to
341
+ be periodically called during the upload.
342
+
343
+ :type Config: boto3.s3.transfer.TransferConfig
344
+ :param Config: The transfer configuration to be used when performing the
345
+ upload.
346
+
347
+ :type Processing: method
348
+ :param Processing: A method which takes a bytes buffer and convert it
349
+ by custom logic.
350
+ """
351
+ kwargs = ExtraArgs or {}
352
+ upload_part_args = {k: v for k, v in kwargs.items() if k in UploadSubmissionTask.UPLOAD_PART_ARGS}
353
+ complete_upload_args = {k: v for k, v in kwargs.items() if k in UploadSubmissionTask.COMPLETE_MULTIPART_ARGS}
354
+ Config = Config or S3TransferConfig()
355
+
356
+ async def fileobj_read(num_bytes: int) -> bytes:
357
+ data = Fileobj.read(num_bytes)
358
+ if inspect.isawaitable(data):
359
+ data = await data
360
+ else:
361
+ await asyncio.sleep(0.0) # Yield to the eventloop incase .read() took ages
362
+
363
+ return data
364
+
365
+ # So some streams might return less than Config.multipart_threshold on a read, but that might not be eof
366
+ initial_data = b''
367
+ while len(initial_data) < Config.multipart_threshold:
368
+ new_data = await fileobj_read(Config.multipart_threshold)
369
+ if new_data == b'':
370
+ break
371
+ initial_data += new_data
372
+
373
+ if len(initial_data) < Config.multipart_threshold:
374
+ # Do Processing hook here, else it'll happen during the multipart
375
+ # upload loop too
376
+ if Processing:
377
+ initial_data = Processing(initial_data)
378
+
379
+ # Do put_object
380
+ await self.put_object(
381
+ Bucket=Bucket,
382
+ Key=Key,
383
+ Body=initial_data,
384
+ **kwargs
385
+ )
386
+ if Callback:
387
+ if inspect.iscoroutinefunction(Callback):
388
+ await Callback(len(initial_data))
389
+ else:
390
+ Callback(len(initial_data))
391
+ return
392
+
393
+ # File bigger than threshold, start multipart upload
394
+ resp = await self.create_multipart_upload(Bucket=Bucket, Key=Key, **kwargs)
395
+ upload_id = resp['UploadId']
396
+ finished_parts = []
397
+ expected_parts = 0
398
+ io_queue = asyncio.Queue(maxsize=Config.max_io_queue_size)
399
+ exception_event = asyncio.Event()
400
+ exception = None
401
+ sent_bytes = 0
402
+
403
+ async def uploader() -> int:
404
+ nonlocal sent_bytes
405
+ nonlocal exception
406
+ uploaded_parts = 0
407
+
408
+ # Loop whilst no other co-routine has raised an exception
409
+ while not exception:
410
+ try:
411
+ part_args = await io_queue.get()
412
+ except asyncio.CancelledError:
413
+ break
414
+
415
+ # Submit part to S3
416
+ try:
417
+ resp = await self.upload_part(**part_args)
418
+ except Exception as err:
419
+ # Set the main exception variable to the current exception, trigger the exception event
420
+ exception = err
421
+ exception_event.set()
422
+ # Exit the coro
423
+ break
424
+
425
+ # Success, add the result to the finished_parts, increment the sent_bytes
426
+
427
+ finished_parts_kwargs = {}
428
+ if 'ChecksumAlgorithm' in kwargs:
429
+ for key in resp:
430
+ if key.startswith('Checksum'):
431
+ finished_parts_kwargs[key] = resp[key]
432
+ finished_parts.append(
433
+ {'ETag': resp['ETag'], 'PartNumber': part_args['PartNumber'], **finished_parts_kwargs})
434
+ current_bytes = len(part_args['Body'])
435
+ sent_bytes += current_bytes
436
+ uploaded_parts += 1
437
+ logger.debug('Uploaded part to S3')
438
+
439
+ # Call the callback, if it blocks then not good :/
440
+ if Callback:
441
+ try:
442
+ if inspect.iscoroutinefunction(Callback):
443
+ await Callback(current_bytes)
444
+ else:
445
+ Callback(current_bytes)
446
+ except: # noqa: E722
447
+ pass
448
+
449
+ # Mark task as done so .join() will work later on
450
+ io_queue.task_done()
451
+
452
+ # For testing return number of parts uploaded
453
+ return uploaded_parts
454
+
455
+ async def file_reader() -> None:
456
+ nonlocal expected_parts
457
+ nonlocal exception
458
+ part = 0
459
+ eof = False
460
+ while not exception and not eof:
461
+ part += 1
462
+ multipart_payload = bytearray()
463
+ if part == 1: # Add in the initial data we've read to check if we've met the multipart threshold
464
+ multipart_payload += initial_data
465
+
466
+ loop_counter = 0
467
+ while len(multipart_payload) < Config.multipart_chunksize:
468
+ try:
469
+ # Handles if .read() returns anything that can be awaited
470
+ data = await fileobj_read(Config.io_chunksize)
471
+ except Exception as err:
472
+ # Caught some random exception whilst reading from a file
473
+ exception = err
474
+ exception_event.set()
475
+
476
+ # shortcircuit upload logic
477
+ eof = True
478
+ multipart_payload = bytearray()
479
+ break
480
+
481
+ if data == b'' and loop_counter > 0: # End of file, handles uploading empty files
482
+ eof = True
483
+ break
484
+ multipart_payload += data
485
+ loop_counter += 1
486
+
487
+ # If file has ended but chunk has some data in it, upload it,
488
+ # else if file ended just after a chunk then exit
489
+ # if the first part is b'' then upload it as we're uploading an empty
490
+ # file
491
+ if not multipart_payload and part != 1:
492
+ break
493
+
494
+ if Processing:
495
+ multipart_payload = Processing(multipart_payload)
496
+
497
+ await io_queue.put({'Body': multipart_payload, 'Bucket': Bucket, 'Key': Key,
498
+ 'PartNumber': part, 'UploadId': upload_id, **upload_part_args})
499
+ logger.debug('Added part to io_queue')
500
+ expected_parts += 1
501
+
502
+ file_reader_future = asyncio.ensure_future(file_reader())
503
+ futures = [asyncio.ensure_future(uploader()) for _ in range(0, Config.max_request_concurrency)]
504
+
505
+ # Wait for file reader to finish
506
+ try:
507
+ await file_reader_future
508
+ except Exception as err:
509
+ # if the file reader raises, we need to clean up the uploaders
510
+ exception = err
511
+ exception_event.set()
512
+ # So by this point all of the file is read and in a queue
513
+
514
+ # wait for either io queue is finished, or an exception has been raised
515
+ _, pending = await asyncio.wait(
516
+ {asyncio.create_task(io_queue.join()), asyncio.create_task(exception_event.wait())},
517
+ return_when=asyncio.FIRST_COMPLETED
518
+ )
519
+
520
+ if exception_event.is_set() or len(finished_parts) != expected_parts:
521
+ # An exception during upload or for some reason the finished parts dont match the expected parts, cancel upload
522
+ await self.abort_multipart_upload(Bucket=Bucket, Key=Key, UploadId=upload_id)
523
+ # Raise exception later after we've disposed of the pending co-routines
524
+ else:
525
+ # All io chunks from the queue have been successfully uploaded
526
+ try:
527
+ # Sort the finished parts as they must be in order
528
+ finished_parts.sort(key=lambda item: item['PartNumber'])
529
+
530
+ await self.complete_multipart_upload(
531
+ Bucket=Bucket,
532
+ Key=Key,
533
+ UploadId=upload_id,
534
+ MultipartUpload={'Parts': finished_parts},
535
+ **complete_upload_args
536
+ )
537
+ except Exception as err:
538
+ # We failed to complete the upload, try and abort, then return the orginal error
539
+ exception = err
540
+ try:
541
+ await self.abort_multipart_upload(Bucket=Bucket, Key=Key, UploadId=upload_id)
542
+ except:
543
+ pass
544
+
545
+ # Close either the Queue.join() coro, or the event.wait() coro
546
+ for coro in pending:
547
+ if not coro.done():
548
+ coro.cancel()
549
+ try:
550
+ await coro
551
+ except:
552
+ pass
553
+
554
+ # Cancel any remaining futures, though if successful they'll be done
555
+ cancelled = []
556
+ for future in futures:
557
+ if not future.done():
558
+ future.cancel()
559
+ cancelled.append(future)
560
+ else:
561
+ uploaded_parts = future.result()
562
+ logger.debug('Future uploaded {0} parts'.format(uploaded_parts))
563
+ if cancelled:
564
+ for uploaded_parts in await asyncio.gather(*cancelled, return_exceptions=True):
565
+ if isinstance(uploaded_parts, int):
566
+ logger.debug('Future uploaded {0} parts'.format(uploaded_parts))
567
+
568
+ # Raise an exception now after everythings cleaned up
569
+ if exception:
570
+ raise exception
571
+
572
+
573
+ @with_current_context(partial(register_feature_id, 'S3_TRANSFER'))
574
+ async def upload_file(
575
+ self,
576
+ Filename: str,
577
+ Bucket: str,
578
+ Key: str,
579
+ ExtraArgs: Optional[Dict[str, Any]] = None,
580
+ Callback: Optional[TransferCallback] = None,
581
+ Config: Optional[S3TransferConfig] = None
582
+ ):
583
+ """Upload a file to an S3 object.
584
+
585
+ Usage::
586
+
587
+ import aioboto3
588
+ async with aioboto3.resource('s3') as s3:
589
+ await s3.meta.client.upload_file('/tmp/hello.txt', 'mybucket', 'hello.txt')
590
+
591
+ Similar behavior as S3Transfer's upload_file() method,
592
+ except that parameters are capitalized.
593
+ """
594
+ async with aiofiles.open(Filename, 'rb') as open_file:
595
+ await upload_fileobj(
596
+ self,
597
+ open_file,
598
+ Bucket,
599
+ Key,
600
+ ExtraArgs=ExtraArgs,
601
+ Callback=Callback,
602
+ Config=Config
603
+ )
604
+
605
+
606
+ @with_current_context(partial(register_feature_id, 'S3_TRANSFER'))
607
+ async def copy(
608
+ self,
609
+ CopySource: Dict[str, Any],
610
+ Bucket: str,
611
+ Key: str,
612
+ ExtraArgs: Optional[Dict[str, Any]] = None,
613
+ Callback: Optional[TransferCallback] = None,
614
+ SourceClient=None, # Should be aioboto3/aiobotocore client
615
+ Config: Optional[S3TransferConfig] = None
616
+ ):
617
+ assert 'Bucket' in CopySource
618
+ assert 'Key' in CopySource
619
+
620
+ SourceClient = SourceClient or self
621
+ Config = Config or S3TransferConfig()
622
+ ExtraArgs = ExtraArgs or {}
623
+
624
+ try:
625
+ head_object_kwargs = {}
626
+ for param, value in ExtraArgs.items():
627
+ if param in CopySubmissionTask.EXTRA_ARGS_TO_HEAD_ARGS_MAPPING:
628
+ head_object_kwargs[CopySubmissionTask.EXTRA_ARGS_TO_HEAD_ARGS_MAPPING[param]] = value
629
+
630
+ # Get object metadata to determine the total size
631
+ head_response = await SourceClient.head_object(Bucket=CopySource['Bucket'], Key=CopySource['Key'], **head_object_kwargs)
632
+ except ClientError as err:
633
+ if err.response['Error']['Code'] == 'NoSuchKey':
634
+ # Convert to 404 so it looks the same when boto3.download_file fails
635
+ raise ClientError({'Error': {'Code': '404', 'Message': 'Not Found'}}, 'HeadObject')
636
+ raise
637
+
638
+ # So CopyObject works up to 5GiB, but S3Transfer uses Config.MultipartThreshold which by default is 8MiB :unamused:
639
+ if head_response['ContentLength'] < Config.multipart_threshold:
640
+ await self.copy_object(CopySource=CopySource, Bucket=Bucket, Key=Key, **ExtraArgs)
641
+ return
642
+
643
+ # File is larger than 5GiB, do multipart copy
644
+ create_multipart_kwargs = {k: v for k, v in ExtraArgs.items() if k not in CopySubmissionTask.CREATE_MULTIPART_ARGS_BLACKLIST}
645
+ create_multipart_upload_resp = await self.create_multipart_upload(Bucket=Bucket, Key=Key, **create_multipart_kwargs)
646
+
647
+ finished_parts = []
648
+ total_size = 0
649
+
650
+ sem = asyncio.Semaphore(Config.max_request_concurrency)
651
+
652
+ async def uploader(size: int, part_args: Dict[str, Any]):
653
+ nonlocal total_size
654
+
655
+ async with sem:
656
+ upload_part_response = await self.upload_part_copy(**part_args)
657
+
658
+ finished_parts.append({'ETag': upload_part_response['CopyPartResult']['ETag'], 'PartNumber': part_args['PartNumber']})
659
+
660
+ # Call the callback, if it blocks then not good :/
661
+ if Callback:
662
+ try:
663
+ total_size += size
664
+ Callback(total_size)
665
+ except: # noqa: E722
666
+ pass
667
+
668
+ num_parts = int(math.ceil(head_response['ContentLength'] / float(Config.multipart_chunksize)))
669
+
670
+ tasks = []
671
+ upload_kwargs = {k: v for k, v in ExtraArgs.items() if k in CopySubmissionTask.UPLOAD_PART_COPY_ARGS}
672
+ upload_kwargs.update({'Bucket': Bucket, 'Key': Key, 'CopySource': CopySource, 'UploadId': create_multipart_upload_resp['UploadId']})
673
+ for part_number in range(1, num_parts + 1):
674
+ part_upload_kwargs = upload_kwargs.copy()
675
+ part_upload_kwargs['PartNumber'] = part_number
676
+
677
+ range_start = (part_number - 1) * Config.multipart_chunksize
678
+ range_end = range_start + Config.multipart_chunksize - 1
679
+ if part_number == num_parts:
680
+ range_end = head_response['ContentLength'] - 1
681
+
682
+ part_upload_kwargs['CopySourceRange'] = f'bytes={range_start}-{range_end}'
683
+
684
+ tasks.append(uploader(range_end-range_start, part_upload_kwargs))
685
+
686
+ try:
687
+ await asyncio.gather(*tasks)
688
+
689
+ assert len(finished_parts) == num_parts, "Number of finished upload parts does not match expected parts"
690
+
691
+ finished_parts.sort(key=lambda item: item['PartNumber'])
692
+
693
+ complete_upload_args = {k: v for k, v in ExtraArgs.items() if k in CopySubmissionTask.COMPLETE_MULTIPART_ARGS}
694
+ await self.complete_multipart_upload(
695
+ Bucket=Bucket,
696
+ Key=Key,
697
+ UploadId=create_multipart_upload_resp['UploadId'],
698
+ MultipartUpload={'Parts': finished_parts},
699
+ **complete_upload_args
700
+ )
701
+
702
+ except Exception as err:
703
+ try:
704
+ await self.abort_multipart_upload(Bucket=Bucket, Key=Key, UploadId=create_multipart_upload_resp['UploadId'])
705
+ except Exception as err2:
706
+ raise err2 from err
707
+ raise err
708
+
709
+
710
+ async def bucket_load(self, *args, **kwargs):
711
+ """
712
+ Calls s3.Client.list_buckets() to update the attributes of the Bucket
713
+ resource.
714
+ """
715
+ # The docstring above is phrased this way to match what the autogenerated
716
+ # docs produce.
717
+
718
+ # We can't actually get the bucket's attributes from a HeadBucket,
719
+ # so we need to use a ListBuckets and search for our bucket.
720
+ # However, we may fail if we lack permissions to ListBuckets
721
+ # or the bucket is in another account. In which case, creation_date
722
+ # will be None.
723
+ self.meta.data = {}
724
+ try:
725
+ response = await self.meta.client.list_buckets()
726
+ for bucket_data in response['Buckets']:
727
+ if bucket_data['Name'] == self.name:
728
+ self.meta.data = bucket_data
729
+ break
730
+ except ClientError as e:
731
+ if not e.response.get('Error', {}).get('Code') == 'AccessDenied':
732
+ raise
data/conda_envs/evalclaw/lib/python3.11/site-packages/h11/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (1.32 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/h11/__pycache__/_abnf.cpython-311.pyc ADDED
Binary file (1.83 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/h11/__pycache__/_connection.cpython-311.pyc ADDED
Binary file (25 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/h11/__pycache__/_events.cpython-311.pyc ADDED
Binary file (15.1 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/h11/__pycache__/_headers.cpython-311.pyc ADDED
Binary file (9.28 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/h11/__pycache__/_readers.cpython-311.pyc ADDED
Binary file (11.1 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/h11/__pycache__/_receivebuffer.cpython-311.pyc ADDED
Binary file (5.16 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/h11/__pycache__/_state.cpython-311.pyc ADDED
Binary file (9.7 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/h11/__pycache__/_util.cpython-311.pyc ADDED
Binary file (5.38 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/h11/__pycache__/_version.cpython-311.pyc ADDED
Binary file (214 Bytes). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/h11/__pycache__/_writers.cpython-311.pyc ADDED
Binary file (7.31 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/jiter/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (353 Bytes). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite-0.47.0.dist-info/licenses/LICENSE ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright (c) 2014, Anaconda Inc.
2
+ All rights reserved.
3
+
4
+ Redistribution and use in source and binary forms, with or without
5
+ modification, are permitted provided that the following conditions are
6
+ met:
7
+
8
+ Redistributions of source code must retain the above copyright notice,
9
+ this list of conditions and the following disclaimer.
10
+
11
+ Redistributions in binary form must reproduce the above copyright
12
+ notice, this list of conditions and the following disclaimer in the
13
+ documentation and/or other materials provided with the distribution.
14
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
15
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
16
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
17
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
18
+ HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
19
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
20
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
data/conda_envs/evalclaw/lib/python3.11/site-packages/llvmlite-0.47.0.dist-info/licenses/LICENSE.thirdparty ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ The llvmlite source tree includes code from LLVM that is governed by the
2
+ following license.
3
+
4
+ ==============================================================================
5
+ The Apache License v2.0 with LLVM Exceptions:
6
+ ==============================================================================
7
+
8
+ Apache License
9
+ Version 2.0, January 2004
10
+ http://www.apache.org/licenses/
11
+
12
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
13
+
14
+ 1. Definitions.
15
+
16
+ "License" shall mean the terms and conditions for use, reproduction,
17
+ and distribution as defined by Sections 1 through 9 of this document.
18
+
19
+ "Licensor" shall mean the copyright owner or entity authorized by
20
+ the copyright owner that is granting the License.
21
+
22
+ "Legal Entity" shall mean the union of the acting entity and all
23
+ other entities that control, are controlled by, or are under common
24
+ control with that entity. For the purposes of this definition,
25
+ "control" means (i) the power, direct or indirect, to cause the
26
+ direction or management of such entity, whether by contract or
27
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
28
+ outstanding shares, or (iii) beneficial ownership of such entity.
29
+
30
+ "You" (or "Your") shall mean an individual or Legal Entity
31
+ exercising permissions granted by this License.
32
+
33
+ "Source" form shall mean the preferred form for making modifications,
34
+ including but not limited to software source code, documentation
35
+ source, and configuration files.
36
+
37
+ "Object" form shall mean any form resulting from mechanical
38
+ transformation or translation of a Source form, including but
39
+ not limited to compiled object code, generated documentation,
40
+ and conversions to other media types.
41
+
42
+ "Work" shall mean the work of authorship, whether in Source or
43
+ Object form, made available under the License, as indicated by a
44
+ copyright notice that is included in or attached to the work
45
+ (an example is provided in the Appendix below).
46
+
47
+ "Derivative Works" shall mean any work, whether in Source or Object
48
+ form, that is based on (or derived from) the Work and for which the
49
+ editorial revisions, annotations, elaborations, or other modifications
50
+ represent, as a whole, an original work of authorship. For the purposes
51
+ of this License, Derivative Works shall not include works that remain
52
+ separable from, or merely link (or bind by name) to the interfaces of,
53
+ the Work and Derivative Works thereof.
54
+
55
+ "Contribution" shall mean any work of authorship, including
56
+ the original version of the Work and any modifications or additions
57
+ to that Work or Derivative Works thereof, that is intentionally
58
+ submitted to Licensor for inclusion in the Work by the copyright owner
59
+ or by an individual or Legal Entity authorized to submit on behalf of
60
+ the copyright owner. For the purposes of this definition, "submitted"
61
+ means any form of electronic, verbal, or written communication sent
62
+ to the Licensor or its representatives, including but not limited to
63
+ communication on electronic mailing lists, source code control systems,
64
+ and issue tracking systems that are managed by, or on behalf of, the
65
+ Licensor for the purpose of discussing and improving the Work, but
66
+ excluding communication that is conspicuously marked or otherwise
67
+ designated in writing by the copyright owner as "Not a Contribution."
68
+
69
+ "Contributor" shall mean Licensor and any individual or Legal Entity
70
+ on behalf of whom a Contribution has been received by Licensor and
71
+ subsequently incorporated within the Work.
72
+
73
+ 2. Grant of Copyright License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ copyright license to reproduce, prepare Derivative Works of,
77
+ publicly display, publicly perform, sublicense, and distribute the
78
+ Work and such Derivative Works in Source or Object form.
79
+
80
+ 3. Grant of Patent License. Subject to the terms and conditions of
81
+ this License, each Contributor hereby grants to You a perpetual,
82
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
83
+ (except as stated in this section) patent license to make, have made,
84
+ use, offer to sell, sell, import, and otherwise transfer the Work,
85
+ where such license applies only to those patent claims licensable
86
+ by such Contributor that are necessarily infringed by their
87
+ Contribution(s) alone or by combination of their Contribution(s)
88
+ with the Work to which such Contribution(s) was submitted. If You
89
+ institute patent litigation against any entity (including a
90
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
91
+ or a Contribution incorporated within the Work constitutes direct
92
+ or contributory patent infringement, then any patent licenses
93
+ granted to You under this License for that Work shall terminate
94
+ as of the date such litigation is filed.
95
+
96
+ 4. Redistribution. You may reproduce and distribute copies of the
97
+ Work or Derivative Works thereof in any medium, with or without
98
+ modifications, and in Source or Object form, provided that You
99
+ meet the following conditions:
100
+
101
+ (a) You must give any other recipients of the Work or
102
+ Derivative Works a copy of this License; and
103
+
104
+ (b) You must cause any modified files to carry prominent notices
105
+ stating that You changed the files; and
106
+
107
+ (c) You must retain, in the Source form of any Derivative Works
108
+ that You distribute, all copyright, patent, trademark, and
109
+ attribution notices from the Source form of the Work,
110
+ excluding those notices that do not pertain to any part of
111
+ the Derivative Works; and
112
+
113
+ (d) If the Work includes a "NOTICE" text file as part of its
114
+ distribution, then any Derivative Works that You distribute must
115
+ include a readable copy of the attribution notices contained
116
+ within such NOTICE file, excluding those notices that do not
117
+ pertain to any part of the Derivative Works, in at least one
118
+ of the following places: within a NOTICE text file distributed
119
+ as part of the Derivative Works; within the Source form or
120
+ documentation, if provided along with the Derivative Works; or,
121
+ within a display generated by the Derivative Works, if and
122
+ wherever such third-party notices normally appear. The contents
123
+ of the NOTICE file are for informational purposes only and
124
+ do not modify the License. You may add Your own attribution
125
+ notices within Derivative Works that You distribute, alongside
126
+ or as an addendum to the NOTICE text from the Work, provided
127
+ that such additional attribution notices cannot be construed
128
+ as modifying the License.
129
+
130
+ You may add Your own copyright statement to Your modifications and
131
+ may provide additional or different license terms and conditions
132
+ for use, reproduction, or distribution of Your modifications, or
133
+ for any such Derivative Works as a whole, provided Your use,
134
+ reproduction, and distribution of the Work otherwise complies with
135
+ the conditions stated in this License.
136
+
137
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
138
+ any Contribution intentionally submitted for inclusion in the Work
139
+ by You to the Licensor shall be under the terms and conditions of
140
+ this License, without any additional terms or conditions.
141
+ Notwithstanding the above, nothing herein shall supersede or modify
142
+ the terms of any separate license agreement you may have executed
143
+ with Licensor regarding such Contributions.
144
+
145
+ 6. Trademarks. This License does not grant permission to use the trade
146
+ names, trademarks, service marks, or product names of the Licensor,
147
+ except as required for reasonable and customary use in describing the
148
+ origin of the Work and reproducing the content of the NOTICE file.
149
+
150
+ 7. Disclaimer of Warranty. Unless required by applicable law or
151
+ agreed to in writing, Licensor provides the Work (and each
152
+ Contributor provides its Contributions) on an "AS IS" BASIS,
153
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
154
+ implied, including, without limitation, any warranties or conditions
155
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
156
+ PARTICULAR PURPOSE. You are solely responsible for determining the
157
+ appropriateness of using or redistributing the Work and assume any
158
+ risks associated with Your exercise of permissions under this License.
159
+
160
+ 8. Limitation of Liability. In no event and under no legal theory,
161
+ whether in tort (including negligence), contract, or otherwise,
162
+ unless required by applicable law (such as deliberate and grossly
163
+ negligent acts) or agreed to in writing, shall any Contributor be
164
+ liable to You for damages, including any direct, indirect, special,
165
+ incidental, or consequential damages of any character arising as a
166
+ result of this License or out of the use or inability to use the
167
+ Work (including but not limited to damages for loss of goodwill,
168
+ work stoppage, computer failure or malfunction, or any and all
169
+ other commercial damages or losses), even if such Contributor
170
+ has been advised of the possibility of such damages.
171
+
172
+ 9. Accepting Warranty or Additional Liability. While redistributing
173
+ the Work or Derivative Works thereof, You may choose to offer,
174
+ and charge a fee for, acceptance of support, warranty, indemnity,
175
+ or other liability obligations and/or rights consistent with this
176
+ License. However, in accepting such obligations, You may act only
177
+ on Your own behalf and on Your sole responsibility, not on behalf
178
+ of any other Contributor, and only if You agree to indemnify,
179
+ defend, and hold each Contributor harmless for any liability
180
+ incurred by, or claims asserted against, such Contributor by reason
181
+ of your accepting any such warranty or additional liability.
182
+
183
+ END OF TERMS AND CONDITIONS
184
+
185
+ APPENDIX: How to apply the Apache License to your work.
186
+
187
+ To apply the Apache License to your work, attach the following
188
+ boilerplate notice, with the fields enclosed by brackets "[]"
189
+ replaced with your own identifying information. (Don't include
190
+ the brackets!) The text should be enclosed in the appropriate
191
+ comment syntax for the file format. We also recommend that a
192
+ file or class name and description of purpose be included on the
193
+ same "printed page" as the copyright notice for easier
194
+ identification within third-party archives.
195
+
196
+ Copyright [yyyy] [name of copyright owner]
197
+
198
+ Licensed under the Apache License, Version 2.0 (the "License");
199
+ you may not use this file except in compliance with the License.
200
+ You may obtain a copy of the License at
201
+
202
+ http://www.apache.org/licenses/LICENSE-2.0
203
+
204
+ Unless required by applicable law or agreed to in writing, software
205
+ distributed under the License is distributed on an "AS IS" BASIS,
206
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
207
+ See the License for the specific language governing permissions and
208
+ limitations under the License.
209
+
210
+
211
+ ---- LLVM Exceptions to the Apache 2.0 License ----
212
+
213
+ As an exception, if, as a result of your compiling your source code, portions
214
+ of this Software are embedded into an Object form of such source code, you
215
+ may redistribute such embedded portions in such Object form without complying
216
+ with the conditions of Sections 4(a), 4(b) and 4(d) of the License.
217
+
218
+ In addition, if you combine or link compiled forms of this Software with
219
+ software that is licensed under the GPLv2 ("Combined Software") and if a
220
+ court of competent jurisdiction determines that the patent provision (Section
221
+ 3), the indemnity provision (Section 9) or other Section of the License
222
+ conflicts with the conditions of the GPLv2, you may retroactively and
223
+ prospectively choose to deem waived or otherwise exclude such Section(s) of
224
+ the License, but only in their entirety and only with respect to the Combined
225
+ Software.
data/conda_envs/evalclaw/lib/python3.11/site-packages/lm_eval/_cli/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (353 Bytes). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/lm_eval/_cli/__pycache__/harness.cpython-311.pyc ADDED
Binary file (4.01 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/lm_eval/_cli/__pycache__/ls.cpython-311.pyc ADDED
Binary file (4.88 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/lm_eval/_cli/__pycache__/run.cpython-311.pyc ADDED
Binary file (18.8 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/lm_eval/_cli/__pycache__/subcommand.cpython-311.pyc ADDED
Binary file (1.32 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/lm_eval/_cli/__pycache__/utils.cpython-311.pyc ADDED
Binary file (9.62 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/lm_eval/_cli/__pycache__/validate.cpython-311.pyc ADDED
Binary file (6.55 kB). View file