-
Notifications
You must be signed in to change notification settings - Fork 1.1k
feat: large file uploads #1255
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
feat: large file uploads #1255
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
356b8f5
chore: roll Playwright to 1.21.0
rwoll f08111f
wip: support large file uploads
rwoll 9c2aa04
remove debug code
rwoll 6df445f
add test, fix WriteableStream
rwoll 6007f81
add remote test
rwoll b232448
s/Writeable/Writable
rwoll 8015d37
mark tests CR only
rwoll 60c3fdc
add WritableStream MVP
rwoll c0aebdb
address review feedback
rwoll 4ff19c6
more pythonic list comprehension
rwoll aed76b5
move copy to WriteableStream class
rwoll da8acd2
add new init script test
rwoll 95a2d3e
fix test_should_be_able_to_reset_selected_files_with_empty_file_list
rwoll File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,101 @@ | ||
import base64 | ||
import os | ||
import sys | ||
from pathlib import Path | ||
from typing import TYPE_CHECKING, List, Optional, Union | ||
|
||
if sys.version_info >= (3, 8): # pragma: no cover | ||
from typing import TypedDict | ||
else: # pragma: no cover | ||
from typing_extensions import TypedDict | ||
|
||
from playwright._impl._connection import Channel, from_channel | ||
from playwright._impl._helper import Error, async_readfile | ||
from playwright._impl._writable_stream import WritableStream | ||
|
||
if TYPE_CHECKING: # pragma: no cover | ||
from playwright._impl._browser_context import BrowserContext | ||
|
||
from playwright._impl._api_structures import FilePayload | ||
|
||
SIZE_LIMIT_IN_BYTES = 50 * 1024 * 1024 | ||
|
||
|
||
class InputFilesList(TypedDict): | ||
streams: Optional[List[Channel]] | ||
localPaths: Optional[List[str]] | ||
files: Optional[List[FilePayload]] | ||
|
||
|
||
async def convert_input_files( | ||
files: Union[str, Path, FilePayload, List[Union[str, Path]], List[FilePayload]], | ||
context: "BrowserContext", | ||
) -> InputFilesList: | ||
file_list = files if isinstance(files, list) else [files] | ||
|
||
has_large_buffer = any( | ||
[ | ||
len(f.get("buffer", "")) > SIZE_LIMIT_IN_BYTES | ||
for f in file_list | ||
if not isinstance(f, (str, Path)) | ||
] | ||
) | ||
if has_large_buffer: | ||
raise Error( | ||
"Cannot set buffer larger than 50Mb, please write it to a file and pass its path instead." | ||
) | ||
|
||
has_large_file = any( | ||
[ | ||
os.stat(f).st_size > SIZE_LIMIT_IN_BYTES | ||
for f in file_list | ||
if isinstance(f, (str, Path)) | ||
] | ||
) | ||
if has_large_file: | ||
if context._channel._connection.is_remote: | ||
streams = [] | ||
for file in file_list: | ||
assert isinstance(file, (str, Path)) | ||
stream: WritableStream = from_channel( | ||
await context._channel.send( | ||
"createTempFile", {"name": os.path.basename(file)} | ||
) | ||
) | ||
await stream.copy(file) | ||
streams.append(stream._channel) | ||
return InputFilesList(streams=streams, localPaths=None, files=None) | ||
local_paths = [] | ||
for p in file_list: | ||
assert isinstance(p, (str, Path)) | ||
local_paths.append(str(Path(p).absolute().resolve())) | ||
return InputFilesList(streams=None, localPaths=local_paths, files=None) | ||
|
||
return InputFilesList( | ||
streams=None, localPaths=None, files=await _normalize_file_payloads(files) | ||
) | ||
|
||
|
||
async def _normalize_file_payloads( | ||
files: Union[str, Path, FilePayload, List[Union[str, Path]], List[FilePayload]] | ||
) -> List: | ||
file_list = files if isinstance(files, list) else [files] | ||
file_payloads: List = [] | ||
for item in file_list: | ||
if isinstance(item, (str, Path)): | ||
file_payloads.append( | ||
{ | ||
"name": os.path.basename(item), | ||
"buffer": base64.b64encode(await async_readfile(item)).decode(), | ||
} | ||
) | ||
else: | ||
file_payloads.append( | ||
{ | ||
"name": item["name"], | ||
"mimeType": item["mimeType"], | ||
"buffer": base64.b64encode(item["buffer"]).decode(), | ||
} | ||
) | ||
|
||
return file_payloads |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
# Copyright (c) Microsoft Corporation. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
import base64 | ||
import os | ||
from pathlib import Path | ||
from typing import Dict, Union | ||
|
||
from playwright._impl._connection import ChannelOwner | ||
|
||
# COPY_BUFSIZE is taken from shutil.py in the standard library | ||
_WINDOWS = os.name == "nt" | ||
COPY_BUFSIZE = 1024 * 1024 if _WINDOWS else 64 * 1024 | ||
|
||
|
||
class WritableStream(ChannelOwner): | ||
def __init__( | ||
self, parent: ChannelOwner, type: str, guid: str, initializer: Dict | ||
) -> None: | ||
super().__init__(parent, type, guid, initializer) | ||
|
||
async def copy(self, path: Union[str, Path]) -> None: | ||
with open(path, "rb") as f: | ||
while True: | ||
data = f.read(COPY_BUFSIZE) | ||
if not data: | ||
break | ||
await self._channel.send( | ||
"write", {"binary": base64.b64encode(data).decode()} | ||
) | ||
await self._channel.send("close") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.