From 817a8814d8b5c0b107c2ea4a35b9f05ada306aa4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 24 Nov 2023 17:33:31 +0100 Subject: [PATCH 1/3] =?UTF-8?q?=E2=AC=86=EF=B8=8F=20Upgrade=20Playwright?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/playwright/package-lock.json | 97 ++++++++++++++++++++---------- tests/playwright/package.json | 2 +- 2 files changed, 67 insertions(+), 32 deletions(-) diff --git a/tests/playwright/package-lock.json b/tests/playwright/package-lock.json index 65d2f2d8e..32e57319a 100644 --- a/tests/playwright/package-lock.json +++ b/tests/playwright/package-lock.json @@ -9,65 +9,100 @@ "version": "1.0.0", "license": "MIT", "devDependencies": { - "@playwright/test": "^1.30.0" + "@playwright/test": "^1.40.0" } }, "node_modules/@playwright/test": { - "version": "1.30.0", - "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.30.0.tgz", - "integrity": "sha512-SVxkQw1xvn/Wk/EvBnqWIq6NLo1AppwbYOjNLmyU0R1RoQ3rLEBtmjTnElcnz8VEtn11fptj1ECxK0tgURhajw==", + "version": "1.40.0", + "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.40.0.tgz", + "integrity": "sha512-PdW+kn4eV99iP5gxWNSDQCbhMaDVej+RXL5xr6t04nbKLCBwYtA046t7ofoczHOm8u6c+45hpDKQVZqtqwkeQg==", "dev": true, "dependencies": { - "@types/node": "*", - "playwright-core": "1.30.0" + "playwright": "1.40.0" }, "bin": { "playwright": "cli.js" }, "engines": { - "node": ">=14" + "node": ">=16" } }, - "node_modules/@types/node": { - "version": "18.11.18", - "resolved": "https://registry.npmjs.org/@types/node/-/node-18.11.18.tgz", - "integrity": "sha512-DHQpWGjyQKSHj3ebjFI/wRKcqQcdR+MoFBygntYOZytCqNfkd2ZC4ARDJ2DQqhjH5p85Nnd3jhUJIXrszFX/JA==", - "dev": true - }, - "node_modules/playwright-core": { - "version": "1.30.0", - "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.30.0.tgz", - "integrity": "sha512-7AnRmTCf+GVYhHbLJsGUtskWTE33SwMZkybJ0v6rqR1boxq2x36U7p1vDRV7HO2IwTZgmycracLxPEJI49wu4g==", + "node_modules/fsevents": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", + "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", "dev": true, + "hasInstallScript": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/playwright": { + "version": "1.40.0", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.40.0.tgz", + "integrity": "sha512-gyHAgQjiDf1m34Xpwzaqb76KgfzYrhK7iih+2IzcOCoZWr/8ZqmdBw+t0RU85ZmfJMgtgAiNtBQ/KS2325INXw==", + "dev": true, + "dependencies": { + "playwright-core": "1.40.0" + }, "bin": { "playwright": "cli.js" }, "engines": { - "node": ">=14" + "node": ">=16" + }, + "optionalDependencies": { + "fsevents": "2.3.2" + } + }, + "node_modules/playwright-core": { + "version": "1.40.0", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.40.0.tgz", + "integrity": "sha512-fvKewVJpGeca8t0ipM56jkVSU6Eo0RmFvQ/MaCQNDYm+sdvKkMBBWTE1FdeMqIdumRaXXjZChWHvIzCGM/tA/Q==", + "dev": true, + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=16" } } }, "dependencies": { "@playwright/test": { - "version": "1.30.0", - "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.30.0.tgz", - "integrity": "sha512-SVxkQw1xvn/Wk/EvBnqWIq6NLo1AppwbYOjNLmyU0R1RoQ3rLEBtmjTnElcnz8VEtn11fptj1ECxK0tgURhajw==", + "version": "1.40.0", + "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.40.0.tgz", + "integrity": "sha512-PdW+kn4eV99iP5gxWNSDQCbhMaDVej+RXL5xr6t04nbKLCBwYtA046t7ofoczHOm8u6c+45hpDKQVZqtqwkeQg==", "dev": true, "requires": { - "@types/node": "*", - "playwright-core": "1.30.0" + "playwright": "1.40.0" } }, - "@types/node": { - "version": "18.11.18", - "resolved": "https://registry.npmjs.org/@types/node/-/node-18.11.18.tgz", - "integrity": "sha512-DHQpWGjyQKSHj3ebjFI/wRKcqQcdR+MoFBygntYOZytCqNfkd2ZC4ARDJ2DQqhjH5p85Nnd3jhUJIXrszFX/JA==", - "dev": true + "fsevents": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", + "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", + "dev": true, + "optional": true + }, + "playwright": { + "version": "1.40.0", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.40.0.tgz", + "integrity": "sha512-gyHAgQjiDf1m34Xpwzaqb76KgfzYrhK7iih+2IzcOCoZWr/8ZqmdBw+t0RU85ZmfJMgtgAiNtBQ/KS2325INXw==", + "dev": true, + "requires": { + "fsevents": "2.3.2", + "playwright-core": "1.40.0" + } }, "playwright-core": { - "version": "1.30.0", - "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.30.0.tgz", - "integrity": "sha512-7AnRmTCf+GVYhHbLJsGUtskWTE33SwMZkybJ0v6rqR1boxq2x36U7p1vDRV7HO2IwTZgmycracLxPEJI49wu4g==", + "version": "1.40.0", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.40.0.tgz", + "integrity": "sha512-fvKewVJpGeca8t0ipM56jkVSU6Eo0RmFvQ/MaCQNDYm+sdvKkMBBWTE1FdeMqIdumRaXXjZChWHvIzCGM/tA/Q==", "dev": true } } diff --git a/tests/playwright/package.json b/tests/playwright/package.json index 3782bf18f..274beb4c5 100644 --- a/tests/playwright/package.json +++ b/tests/playwright/package.json @@ -8,6 +8,6 @@ "author": "Gina Häußge", "license": "MIT", "devDependencies": { - "@playwright/test": "^1.30.0" + "@playwright/test": "^1.40.0" } } From 703ec2da4cc2f34dcdaf35a36805ff6bedd1230c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 23 Nov 2023 17:11:46 +0100 Subject: [PATCH 2/3] =?UTF-8?q?=E2=9A=A1=EF=B8=8F=20Make=20WSGIContainer?= =?UTF-8?q?=20use=20threads=20for=20async=20handling?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Copied from current tornado.wsgi.WSGIContainer. Seems to solve to not delete the tmp files too early. Also turned UploadStorageFallbackHandler async, otherwise connections would be closed too early, causing issues in E2E and probably also regular use. --- src/octoprint/server/__init__.py | 14 ++- src/octoprint/server/util/tornado.py | 136 ++++++++++++++++++--------- 2 files changed, 102 insertions(+), 48 deletions(-) diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 2fcca6f1b..0f8928f5c 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -677,10 +677,7 @@ class Server: ## Tornado initialization starts here - ioloop = ( - IOLoop() - ) # TODO: This way to create the ioloop is deprecated and logs a warning - ioloop.install() + ioloop = IOLoop.current() enable_cors = settings().getBoolean(["api", "allowCrossOrigin"]) @@ -1020,13 +1017,20 @@ class Server: removed_headers = ["Server"] + from concurrent.futures import ThreadPoolExecutor + server_routes.append( ( r".*", util.tornado.UploadStorageFallbackHandler, { "fallback": util.tornado.WsgiInputContainer( - app.wsgi_app, headers=headers, removed_headers=removed_headers + app.wsgi_app, + executor=ThreadPoolExecutor( + thread_name_prefix="WsgiRequestHandler" + ), + headers=headers, + removed_headers=removed_headers, ), "file_prefix": "octoprint-file-upload-", "file_suffix": ".tmp", diff --git a/src/octoprint/server/util/tornado.py b/src/octoprint/server/util/tornado.py index a5bf04adb..3ab3bf621 100644 --- a/src/octoprint/server/util/tornado.py +++ b/src/octoprint/server/util/tornado.py @@ -20,6 +20,8 @@ import tornado.iostream import tornado.tcpserver import tornado.util import tornado.web +from tornado.concurrent import dummy_executor +from tornado.ioloop import IOLoop from zipstream.ng import ZIP_DEFLATED, ZipStream import octoprint.util @@ -562,7 +564,7 @@ class UploadStorageFallbackHandler(RequestlessExceptionLoggingMixin, CorsSupport self._new_body += value + b"\r\n" self._new_body += b"--%s--\r\n" % self._multipart_boundary - def _handle_method(self, *args, **kwargs): + async def _handle_method(self, *args, **kwargs): """ Takes care of defining the new request body if necessary and forwarding the current request and changed body to the ``fallback``. @@ -582,17 +584,24 @@ class UploadStorageFallbackHandler(RequestlessExceptionLoggingMixin, CorsSupport # directly use data from buffer body = self._buffer - # rewrite content length self.request.headers["Content-Length"] = len(body) try: # call the configured fallback with request and body to use - self._fallback(self.request, body) - self._headers_written = True + result = self._fallback(self.request, body) + if result is not None: + await result + # self._headers_written = True finally: # make sure the temporary files are removed again - for f in self._files: - octoprint.util.silent_remove(f) + self._cleanup_files() + + def _cleanup_files(self): + """ + Removes all temporary files created by this handler. + """ + for f in self._files: + octoprint.util.silent_remove(f) # make all http methods trigger _handle_method get = _handle_method @@ -663,12 +672,21 @@ class WsgiInputContainer: The implementation logic is basically the same as ``tornado.wsgi.WSGIContainer`` but the ``__call__`` and ``environ`` methods have been adjusted to allow for an optionally supplied ``body`` argument which is then used for ``wsgi.input``. + + Additionally, some headers can be added or removed from the response by supplying ``forced_headers`` and + ``removed_headers`` arguments. ``forced_headers`` will be added to the response, ``removed_headers`` will be removed. """ def __init__( - self, wsgi_application, headers=None, forced_headers=None, removed_headers=None + self, + wsgi_application, + executor=None, + headers=None, + forced_headers=None, + removed_headers=None, ): self.wsgi_application = wsgi_application + self.executor = dummy_executor if executor is None else executor if headers is None: headers = {} @@ -682,11 +700,19 @@ class WsgiInputContainer: self.removed_headers = removed_headers def __call__(self, request, body=None): + future = tornado.concurrent.Future() + IOLoop.current().spawn_callback( + self.handle_request, request, body=body, future=future + ) + return future + + async def handle_request(self, request, body=None, future=None): """ Wraps the call against the WSGI app, deriving the WSGI environment from the supplied Tornado ``HTTPServerRequest``. :param request: the ``tornado.httpserver.HTTPServerRequest`` to derive the WSGI environment from :param body: an optional body to use as ``wsgi.input`` instead of ``request.body``, can be a string or a stream + :param future: a future to complete after the request has been handled """ data = {} @@ -697,48 +723,72 @@ class WsgiInputContainer: data["headers"] = response_headers return response.append - app_response = self.wsgi_application( - WsgiInputContainer.environ(request, body), start_response - ) try: - response.extend(app_response) + loop = IOLoop.current() + app_response = await loop.run_in_executor( + self.executor, + self.wsgi_application, + self.environ(request, body), + start_response, + ) + try: + app_response_iter = iter(app_response) + + def next_chunk(): + try: + return next(app_response_iter) + except StopIteration: + return None + + while True: + chunk = await loop.run_in_executor(self.executor, next_chunk) + if chunk is None: + break + response.append(chunk) + finally: + if hasattr(app_response, "close"): + app_response.close() body = b"".join(response) - finally: - if hasattr(app_response, "close"): - app_response.close() - if not data: - raise Exception("WSGI app did not call start_response") + if not data: + raise Exception("WSGI app did not call start_response") - status_code, reason = data["status"].split(" ", 1) - status_code = int(status_code) - headers = data["headers"] - header_set = {k.lower() for (k, v) in headers} - body = tornado.escape.utf8(body) - if status_code != 304: - if "content-length" not in header_set: - headers.append(("Content-Length", str(len(body)))) - if "content-type" not in header_set: - headers.append(("Content-Type", "text/html; charset=UTF-8")) + status_code_str, reason = data["status"].split(" ", 1) + status_code = int(status_code_str) + headers = data["headers"] + header_set = {k.lower() for (k, v) in headers} + body = tornado.escape.utf8(body) + if status_code != 304: + if "content-length" not in header_set: + headers.append(("Content-Length", str(len(body)))) + if "content-type" not in header_set: + headers.append(("Content-Type", "text/html; charset=UTF-8")) - header_set = {k.lower() for (k, v) in headers} - for header, value in self.headers.items(): - if header.lower() not in header_set: + header_set = {k.lower() for (k, v) in headers} + for header, value in self.headers.items(): + if header.lower() not in header_set: + headers.append((header, value)) + for header, value in self.forced_headers.items(): headers.append((header, value)) - for header, value in self.forced_headers.items(): - headers.append((header, value)) - headers = [ - (header, value) - for header, value in headers - if header.lower() not in self.removed_headers - ] + headers = [ + (header, value) + for header, value in headers + if header.lower() not in self.removed_headers + ] - start_line = tornado.httputil.ResponseStartLine("HTTP/1.1", status_code, reason) - header_obj = tornado.httputil.HTTPHeaders() - for key, value in headers: - header_obj.add(key, value) - request.connection.write_headers(start_line, header_obj, chunk=body) - request.connection.finish() - self._log(status_code, request) + start_line = tornado.httputil.ResponseStartLine( + "HTTP/1.1", status_code, reason + ) + header_obj = tornado.httputil.HTTPHeaders() + for key, value in headers: + header_obj.add(key, value) + assert request.connection is not None + request.connection.write_headers(start_line, header_obj, chunk=body) + request.connection.finish() + self._log(status_code, request) + + finally: + if future is not None: + future.set_result(None) @staticmethod def environ(request, body=None): From 33525e46f96a2977815c06b0a6732a5bc0017e36 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 27 Nov 2023 16:59:23 +0100 Subject: [PATCH 3/3] =?UTF-8?q?=F0=9F=A7=91=E2=80=8D=F0=9F=92=BB=20virtual?= =?UTF-8?q?:=20Configuration=20of=20simulated=20errors?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/development/virtual_printer.rst | 11 ++- .../plugins/virtual_printer/__init__.py | 6 ++ .../plugins/virtual_printer/virtual.py | 83 +++++++++---------- 3 files changed, 56 insertions(+), 44 deletions(-) diff --git a/docs/development/virtual_printer.rst b/docs/development/virtual_printer.rst index d90817f9b..c93b41fcf 100644 --- a/docs/development/virtual_printer.rst +++ b/docs/development/virtual_printer.rst @@ -210,8 +210,8 @@ There many configuration options via ``config.yaml`` for the virtual printer tha EXTENDED_M20: false LFN_WRITE: false - # Whether to include area report in the M115 output (M115_GEOMETRY_REPORT in Marlin) - m115ReportArea: false + # Whether to include area report in the M115 output (M115_GEOMETRY_REPORT in Marlin) + m115ReportArea: false # Simulated ambient temperature in °C ambientTemperature: 21.3 @@ -241,6 +241,13 @@ There many configuration options via ``config.yaml`` for the virtual printer tha # Resend ratio to simulate noise on the line resend_ratio: 0 + # communication errors to simulate at specific line numbers + simulated_errors: + - 100:resend # requests a simple resend at line 100 + - 105:resend_with_timeout # requests a resend at line 105 and simulates not responding to it + - 110:missing_lineno # simulates a missing line number at line 110 + - 115:checksum_mismatch # simulates a checksum mismatch at line 115 + .. _sec-development-virtual-printer-log: Log file diff --git a/src/octoprint/plugins/virtual_printer/__init__.py b/src/octoprint/plugins/virtual_printer/__init__.py index e10fd6e0a..73b6217af 100644 --- a/src/octoprint/plugins/virtual_printer/__init__.py +++ b/src/octoprint/plugins/virtual_printer/__init__.py @@ -75,6 +75,12 @@ class VirtualPrinterPlugin( "resend_ratio": 0, "locked": False, "passcode": "1234", + "simulated_errors": [ + "100:resend", + "105:resend_with_timeout", + "110:missing_lineno", + "115:checksum_mismatch", + ], } def get_settings_version(self): diff --git a/src/octoprint/plugins/virtual_printer/virtual.py b/src/octoprint/plugins/virtual_printer/virtual.py index 28db7ad3e..fba3678cd 100644 --- a/src/octoprint/plugins/virtual_printer/virtual.py +++ b/src/octoprint/plugins/virtual_printer/virtual.py @@ -200,10 +200,18 @@ class VirtualPrinter: self._killed = False - self._triggerResendAt100 = True - self._triggerResendWithTimeoutAt105 = True - self._triggerResendWithMissingLinenoAt110 = True - self._triggerResendWithChecksumMismatchAt115 = True + self._simulated_errors = {} + for v in self._settings.get(["simulated_errors"]): + if ":" not in v: + continue + try: + k, v = v.split(":", 1) + k = int(k) + self._simulated_errors[k] = v + except ValueError: + # ignore this, it's not a valid entry + pass + self._already_simulated_errors = set() readThread = threading.Thread( target=self._processIncoming, @@ -281,10 +289,7 @@ class VirtualPrinter: self._killed = False - self._triggerResendAt100 = True - self._triggerResendWithTimeoutAt105 = True - self._triggerResendWithMissingLinenoAt110 = True - self._triggerResendWithChecksumMismatchAt115 = True + self._already_simulated_errors.clear() if self._temperature_reporter is not None: self._temperature_reporter.cancel() @@ -401,50 +406,41 @@ class VirtualPrinter: linenumber = int(re.search(b"N([0-9]+)", data).group(1)) self.lastN = linenumber self.current_line = linenumber - - self._triggerResendAt100 = True - self._triggerResendWithTimeoutAt105 = True - self._sendOk() + self._already_simulated_errors.clear() continue + elif data.startswith(b"N"): linenumber = int(re.search(b"N([0-9]+)", data).group(1)) expected = self.lastN + 1 if linenumber != expected: self._triggerResend(actual=linenumber) continue - elif linenumber == 100 and self._triggerResendAt100: - # simulate a resend at line 100 - self._triggerResendAt100 = False - self._triggerResend(expected=100) - continue + elif ( - linenumber == 105 - and self._triggerResendWithTimeoutAt105 - and not self._writingToSd + linenumber in self._simulated_errors + and linenumber not in self._already_simulated_errors ): - # simulate a resend with timeout at line 105 - self._triggerResendWithTimeoutAt105 = False - self._triggerResend(expected=105) - self._dont_answer = True - self.lastN = linenumber - continue - elif ( - linenumber == 110 - and self._triggerResendWithMissingLinenoAt110 - and not self._writingToSd - ): - self._triggerResendWithMissingLinenoAt110 = False - self._send(self._error("lineno_missing", self.lastN)) - continue - elif ( - linenumber == 115 - and self._triggerResendWithChecksumMismatchAt115 - and not self._writingToSd - ): - self._triggerResendWithChecksumMismatchAt115 = False - self._triggerResend(checksum=True) - continue + action = self._simulated_errors[linenumber] + if action == "resend": + self._triggerResend(expected=linenumber) + self._already_simulated_errors.add(linenumber) + continue + elif action == "resend_with_timeout" and not self._writingToSd: + self._triggerResend(expected=linenumber) + self._dont_answer = True + self.lastN = linenumber + self._already_simulated_errors.add(linenumber) + continue + elif action == "missing_lineno" and not self._writingToSd: + self._send(self._error("lineno_missing", self.lastN)) + self._already_simulated_errors.add(linenumber) + continue + elif action == "checksum_mismatch" and not self._writingToSd: + self._triggerResend(checksum=True) + self._already_simulated_errors.add(linenumber) + continue + elif len(self._prepared_errors): prepared = self._prepared_errors.pop(0) if callable(prepared): @@ -453,11 +449,14 @@ class VirtualPrinter: elif isinstance(prepared, str): self._send(prepared) continue + elif self._rerequest_last: self._triggerResend(actual=linenumber) continue + else: self.lastN = linenumber + data = data.split(None, 1)[1].strip() data += b"\n"