flet-web 1.1.0.dev2__py3-none-any.whl → 1.1.0.dev4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,101 @@
1
+ import gzip
2
+ import os
3
+ import shutil
4
+
5
+ COMPRESSIBLE_EXTENSIONS = {
6
+ ".css",
7
+ ".html",
8
+ ".js",
9
+ ".json",
10
+ ".map",
11
+ ".mjs",
12
+ ".otf",
13
+ ".svg",
14
+ ".ttf",
15
+ ".txt",
16
+ ".wasm",
17
+ ".xml",
18
+ }
19
+ """
20
+ Extensions of files sent gzip-compressed to browsers that accept it.
21
+
22
+ Text and WebAssembly files shrink about 3x with gzip; images, archives and
23
+ `.woff2` fonts are already compressed.
24
+ """
25
+
26
+ MIN_COMPRESSED_FILE_SIZE = 1024
27
+ """
28
+ Size in bytes below which files are sent uncompressed, as compression saves less
29
+ than it costs.
30
+ """
31
+
32
+
33
+ def is_compressible(path: str, stat_result: os.stat_result) -> bool:
34
+ """
35
+ Whether a static file is served gzip-compressed to browsers that accept it.
36
+
37
+ Args:
38
+ path: Path of the file.
39
+ stat_result: The file's `os.stat()` result.
40
+ """
41
+
42
+ return (
43
+ os.path.splitext(path)[1].lower() in COMPRESSIBLE_EXTENSIONS
44
+ and stat_result.st_size >= MIN_COMPRESSED_FILE_SIZE
45
+ )
46
+
47
+
48
+ def accepts_gzip(accept_encoding: str) -> bool:
49
+ """
50
+ Whether an `Accept-Encoding` request header allows a gzip response.
51
+
52
+ Args:
53
+ accept_encoding: Value of the header, e.g. `"gzip, deflate, br"`.
54
+
55
+ Returns:
56
+ `True` if `gzip`, or else `*`, is listed without `q=0`.
57
+ """
58
+
59
+ qualities = {}
60
+ for coding in accept_encoding.split(","):
61
+ name, *params = coding.split(";")
62
+ quality = 1.0
63
+ for param in params:
64
+ key, _, value = param.partition("=")
65
+ if key.strip().lower() == "q":
66
+ try:
67
+ quality = float(value)
68
+ except ValueError:
69
+ quality = 0.0
70
+ qualities[name.strip().lower()] = quality
71
+ return qualities.get("gzip", qualities.get("*", 0.0)) > 0
72
+
73
+
74
+ def write_gzip(source: str, target: str, stat_result: os.stat_result):
75
+ """
76
+ Write a gzip-compressed copy of a file.
77
+
78
+ The copy gets the source's modification time, so that it is served with the
79
+ same `Last-Modified` header. A copy left unfinished by an error is removed.
80
+
81
+ Args:
82
+ source: Path of the file to compress.
83
+ target: Path of the compressed copy.
84
+ stat_result: The source's `os.stat()` result.
85
+ """
86
+
87
+ temp = f"{target}.tmp"
88
+ try:
89
+ with (
90
+ open(source, "rb") as src,
91
+ open(temp, "wb") as raw,
92
+ gzip.GzipFile(
93
+ filename="", mode="wb", compresslevel=6, fileobj=raw, mtime=0
94
+ ) as dst,
95
+ ):
96
+ shutil.copyfileobj(src, dst)
97
+ os.utime(temp, ns=(stat_result.st_atime_ns, stat_result.st_mtime_ns))
98
+ os.replace(temp, target)
99
+ finally:
100
+ if os.path.exists(temp):
101
+ os.remove(temp)
@@ -1,12 +1,19 @@
1
+ import hashlib
1
2
  import logging
2
3
  import mimetypes
3
4
  import os
4
5
  import shutil
5
6
  import tempfile
7
+ from email.utils import parsedate
6
8
  from pathlib import Path
7
- from typing import Optional
9
+ from typing import Optional, Union
8
10
 
11
+ import anyio
12
+ import anyio.to_thread
9
13
  from fastapi.staticfiles import StaticFiles
14
+ from starlette.datastructures import Headers
15
+ from starlette.responses import FileResponse, Response
16
+ from starlette.staticfiles import NotModifiedResponse
10
17
  from starlette.types import Receive, Scope, Send
11
18
 
12
19
  import flet_web.fastapi as flet_fastapi
@@ -18,6 +25,7 @@ from flet_web import (
18
25
  patch_index_html,
19
26
  patch_manifest_json,
20
27
  )
28
+ from flet_web.compression import accepts_gzip, is_compressible, write_gzip
21
29
  from flet_web.fastapi.flet_app_manager import app_manager
22
30
 
23
31
  logger = logging.getLogger(flet_fastapi.__name__)
@@ -63,6 +71,13 @@ class FletStaticFiles(StaticFiles):
63
71
  """
64
72
  Serve Flet app static files.
65
73
 
74
+ Text and WebAssembly files, like the web client's `main.dart.wasm` and
75
+ `main.dart.js`, are sent gzip-compressed to browsers that accept it, which
76
+ makes them about 3x smaller to download. Each file is compressed once, in a
77
+ worker thread, on its first request, and the compressed copy is kept in a
78
+ temporary directory until the server exits. Byte range requests get the
79
+ uncompressed file.
80
+
66
81
  Args:
67
82
  assets_dir: Path to app's assets directory. A relative path is resolved
68
83
  against the current working directory.
@@ -104,6 +119,9 @@ class FletStaticFiles(StaticFiles):
104
119
  self.__no_cdn = no_cdn
105
120
  self.__websocket_endpoint_path = websocket_endpoint_path
106
121
  self.__once = Once()
122
+ self.__gzip_dir: Optional[str] = None
123
+ self.__gzip_locks: dict[str, anyio.Lock] = {}
124
+ self.__gzip_failures: set[str] = set()
107
125
 
108
126
  env_web_renderer = os.getenv("FLET_WEB_RENDERER")
109
127
  if env_web_renderer:
@@ -133,6 +151,167 @@ class FletStaticFiles(StaticFiles):
133
151
  await self.__once.do(self.__config, scope["root_path"])
134
152
  await super().__call__(scope, receive, send)
135
153
 
154
+ def file_response(
155
+ self,
156
+ full_path: Union[str, os.PathLike[str]],
157
+ stat_result: os.stat_result,
158
+ scope: Scope,
159
+ status_code: int = 200,
160
+ ) -> Response:
161
+ """
162
+ Respond with a static file, adding `Vary: Accept-Encoding` to
163
+ compressible ones.
164
+
165
+ Unlike `StaticFiles`, this never responds with `304 Not Modified`:
166
+ `get_response()` checks the browser's cached copy once it has picked
167
+ the plain or compressed file.
168
+ """
169
+ response = FileResponse(
170
+ full_path, status_code=status_code, stat_result=stat_result
171
+ )
172
+ if is_compressible(str(full_path), stat_result):
173
+ # Tells caches that the response depends on the browser's
174
+ # `Accept-Encoding`, so they keep the plain and gzip versions apart.
175
+ response.headers["Vary"] = "Accept-Encoding"
176
+ return response
177
+
178
+ async def get_response(self, path: str, scope: Scope) -> Response:
179
+ """
180
+ Respond with a static file, gzip-compressed if the browser accepts it.
181
+
182
+ Args:
183
+ path: Requested path, relative to the mounted static root.
184
+ scope: ASGI request scope.
185
+
186
+ Returns:
187
+ The compressed file for a `200` response of a compressible file to a
188
+ request that accepts gzip and has no `Range` header; otherwise
189
+ the response of `StaticFiles`. Either is `304 Not Modified` if
190
+ the browser has that same file cached.
191
+ """
192
+
193
+ response = await super().get_response(path, scope)
194
+ if response.status_code != 200 or not isinstance(response, FileResponse):
195
+ return response
196
+
197
+ request_headers = Headers(scope=scope)
198
+ if (
199
+ response.stat_result is not None
200
+ and is_compressible(str(response.path), response.stat_result)
201
+ and "range" not in request_headers
202
+ and accepts_gzip(request_headers.get("accept-encoding", ""))
203
+ ):
204
+ # Derived from the plain file's `ETag`, so it changes whenever the
205
+ # file does, and never equals it.
206
+ etag = response.headers["etag"].removesuffix('"') + '-gzip"'
207
+ gzip_headers = Headers(
208
+ {
209
+ "etag": etag,
210
+ "last-modified": response.headers["last-modified"],
211
+ "vary": "Accept-Encoding",
212
+ }
213
+ )
214
+ # Checked before compressing, so a browser revalidating its copy
215
+ # after a server restart doesn't wait for the file to be compressed.
216
+ if self.is_not_modified(gzip_headers, request_headers):
217
+ return NotModifiedResponse(gzip_headers)
218
+
219
+ compressed = await self.__compress(str(response.path), response.stat_result)
220
+ if compressed:
221
+ gzip_path, gzip_stat = compressed
222
+ response = FileResponse(
223
+ gzip_path,
224
+ stat_result=gzip_stat,
225
+ media_type=response.media_type,
226
+ headers={
227
+ "Content-Encoding": "gzip",
228
+ "ETag": etag,
229
+ "Vary": "Accept-Encoding",
230
+ },
231
+ )
232
+
233
+ if self.is_not_modified(response.headers, request_headers):
234
+ return NotModifiedResponse(response.headers)
235
+ return response
236
+
237
+ def is_not_modified(
238
+ self, response_headers: Headers, request_headers: Headers
239
+ ) -> bool:
240
+ """
241
+ Whether the browser's cached copy of a file is still current.
242
+
243
+ `If-None-Match`, when sent, decides alone, so a cached copy in the
244
+ other encoding, which has the same `Last-Modified`, is never taken as
245
+ current.
246
+
247
+ Args:
248
+ response_headers: Headers of the response that would be sent.
249
+ request_headers: Headers of the request.
250
+ """
251
+
252
+ if if_none_match := request_headers.get("if-none-match"):
253
+ tags = [tag.strip().removeprefix("W/") for tag in if_none_match.split(",")]
254
+ return response_headers["etag"] in tags or "*" in tags
255
+
256
+ if_modified_since = parsedate(request_headers.get("if-modified-since", ""))
257
+ last_modified = parsedate(response_headers.get("last-modified", ""))
258
+ return (
259
+ if_modified_since is not None
260
+ and last_modified is not None
261
+ and if_modified_since >= last_modified
262
+ )
263
+
264
+ async def __compress(
265
+ self, path: str, stat_result: os.stat_result
266
+ ) -> Optional[tuple[str, os.stat_result]]:
267
+ """
268
+ Get the gzip-compressed copy of a file, compressing it first if needed.
269
+
270
+ Copies are keyed by the file's identity on disk, size and modification
271
+ time: a file changed while the server runs is compressed again, and
272
+ paths that name the same file, such as differently cased ones on a
273
+ case-insensitive file system, share one copy. Concurrent requests for
274
+ the same file wait for one compression. A file that fails to compress
275
+ is logged and not tried again until it changes.
276
+
277
+ Args:
278
+ path: Path of the file.
279
+ stat_result: The file's `os.stat()` result.
280
+
281
+ Returns:
282
+ The path and `os.stat()` result of the compressed copy, or `None` if
283
+ the file could not be compressed.
284
+ """
285
+
286
+ assert self.__gzip_dir
287
+ identity = (
288
+ f"{stat_result.st_dev}:{stat_result.st_ino}"
289
+ if stat_result.st_ino
290
+ else os.path.normcase(os.path.realpath(path))
291
+ )
292
+ key = hashlib.sha256(
293
+ f"{identity}\0{stat_result.st_size}\0{stat_result.st_mtime_ns}".encode()
294
+ ).hexdigest()
295
+ if key in self.__gzip_failures:
296
+ return None
297
+ gzip_path = os.path.join(self.__gzip_dir, f"{key}.gz")
298
+
299
+ def compress() -> os.stat_result:
300
+ if not os.path.exists(gzip_path):
301
+ write_gzip(path, gzip_path, stat_result)
302
+ return os.stat(gzip_path)
303
+
304
+ lock = self.__gzip_locks.setdefault(key, anyio.Lock())
305
+ async with lock:
306
+ if key in self.__gzip_failures:
307
+ return None
308
+ try:
309
+ return gzip_path, await anyio.to_thread.run_sync(compress)
310
+ except OSError as e:
311
+ logger.warning(f"Could not compress {path}: {e}")
312
+ self.__gzip_failures.add(key)
313
+ return None
314
+
136
315
  def lookup_path(self, path: str) -> tuple[str, Optional[os.stat_result]]:
137
316
  """Resolve a static file path, with SPA fallback for client-side routes.
138
317
 
@@ -195,6 +374,11 @@ class FletStaticFiles(StaticFiles):
195
374
  app_manager.add_temp_dir(temp_dir)
196
375
  logger.info(f"Temp dir created for patched index and manifest: {temp_dir}")
197
376
 
377
+ # where gzip-compressed copies of served files are stored; outside
378
+ # temp_dir, which is served
379
+ self.__gzip_dir = tempfile.mkdtemp()
380
+ app_manager.add_temp_dir(self.__gzip_dir)
381
+
198
382
  # "standard" web files
199
383
  web_dir = get_package_web_dir()
200
384
  if os.getenv("FLET_WEB_PATH"):
flet_web/version.py CHANGED
@@ -1 +1 @@
1
- version = "1.1.0.dev2"
1
+ version = "1.1.0.dev4"
@@ -38,7 +38,7 @@ addEventListener("message", eventListener);
38
38
  if (!window._flutter) {
39
39
  window._flutter = {};
40
40
  }
41
- _flutter.buildConfig = {"engineRevision":"deb287481e3ce9468f3434937ced4240a70539ca","wasmHashes":{"skwasm.wasm":"e540fd5e8303b7b68ec2718cb49e9c421f8ade3075b15e02a7059a62654df9a1","canvaskit.wasm":"fbed517a43e82452404446683f00f2e876d835aed84410695759e67b6bb01cd3","wimp.wasm":"e924eaafd801d41e017d178f3fd5cf8a417f641fe35c9ed34a4e1d7582283e0c","skwasm_heavy.wasm":"565f5cc1cca6ab120f11934b105f01fec4b58b480c82e0889dca93af8e6f8635","chromium/canvaskit.wasm":"ae8ff1d858140f7b1300ced3fa89fb8c9dce0a400a0f4f1e11f6dcfb3315fdcf","webparagraph/canvaskit.wasm":"0ce1b05082efdc8529550e8a01f6ff0593972d55525035010e26f5600aa9f254"},"builds":[{"compileTarget":"dart2wasm","renderer":"skwasm","mainWasmPath":"main.dart.wasm","jsSupportRuntimePath":"main.dart.mjs"},{"compileTarget":"dart2js","renderer":"canvaskit","mainJsPath":"main.dart.js"}]};
41
+ _flutter.buildConfig = {"engineRevision":"89c39edfdfae2949f6806e4a315c0c08522238b7","wasmHashes":{"skwasm.wasm":"e540fd5e8303b7b68ec2718cb49e9c421f8ade3075b15e02a7059a62654df9a1","canvaskit.wasm":"fbed517a43e82452404446683f00f2e876d835aed84410695759e67b6bb01cd3","wimp.wasm":"e924eaafd801d41e017d178f3fd5cf8a417f641fe35c9ed34a4e1d7582283e0c","skwasm_heavy.wasm":"565f5cc1cca6ab120f11934b105f01fec4b58b480c82e0889dca93af8e6f8635","chromium/canvaskit.wasm":"ae8ff1d858140f7b1300ced3fa89fb8c9dce0a400a0f4f1e11f6dcfb3315fdcf","webparagraph/canvaskit.wasm":"0ce1b05082efdc8529550e8a01f6ff0593972d55525035010e26f5600aa9f254"},"builds":[{"compileTarget":"dart2wasm","renderer":"skwasm","mainWasmPath":"main.dart.wasm","jsSupportRuntimePath":"main.dart.mjs"},{"compileTarget":"dart2js","renderer":"canvaskit","mainJsPath":"main.dart.js"}]};
42
42
 
43
43
 
44
44
  window.addEventListener('flutter-first-frame', () => {
@@ -67,7 +67,7 @@ if (flet.fontFallbackBaseUrl) {
67
67
  _flutter.loader.load({
68
68
  config: flutterConfig,
69
69
  serviceWorkerSettings: {
70
- serviceWorkerVersion: "1176238252" /* Flutter's service worker is deprecated and will be removed in a future Flutter release. */,
70
+ serviceWorkerVersion: "1767271274" /* Flutter's service worker is deprecated and will be removed in a future Flutter release. */,
71
71
  },
72
72
  onEntrypointLoaded: async function (engineInitializer) {
73
73
  const engine = await engineInitializer.initializeEngine(flutterConfig);