FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
pythonnative/src/pythonnative/devserver/server.py at main · pythonnative/pythonnative · GitHub
pythonnative
/
pythonnative
Public
Notifications
You must be signed in to change notification settings
Fork
23
Star
131
Code
Issues
11
Pull requests
4
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
pythonnative
/
src
/
pythonnative
/
devserver
/
server.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
876 lines (775 loc) · 32.5 KB
Breadcrumbs
pythonnative
/
src
/
pythonnative
/
devserver
/
server.py
Copy path
File metadata and controls
876 lines (775 loc) · 32.5 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
"""The dev server: HTTP for static assets, WebSocket for live peers.
One [`DevServer`][pythonnative.devserver.server.DevServer] runs on its
own thread with a private ``asyncio`` loop, so it works both inside
``pn start`` and in tests independently of the Python application
loop. It exposes:
- ``GET /``: the browser preview page. With a valid ``?token=``, the
response instead sets the ``pn_token`` cookie and redirects to ``/``,
so the token doesn't stay in the address bar.
- ``GET /static/<name>``: preview assets (JS, CSS).
- ``GET /manifest``: ``{"version", "entry", "files": {path: sha256}}``.
- ``GET /file/<path>``: raw bytes of one synced source file.
- ``GET /assets/<path>``: a file under ``app/assets/``; ``/assets/pn_assets.json``
is the asset manifest and ``/assets/fonts.css`` declares the bundled
fonts for the browser preview.
- ``GET /status``: server, project, and connected-peer information.
- ``WS /ws?role=client``: the dev-client protocol (see below).
- ``WS /ws?role=preview``: the browser preview's bridge channel; the
server only relays text frames between the page and the
[`PreviewChannel`][pythonnative.devserver.server.PreviewChannel]
handler installed by the preview.
Every route except the page and ``/static/`` requires the per-user dev
token (see ``pythonnative.devserver.auth``) as a ``token`` query
parameter, an ``X-PN-Token`` header, or the ``pn_token`` cookie.
Requests without it get ``401``; requests with a wrong one get ``403``.
A WebSocket upgrade that carries an ``Origin`` header (every browser
sends one) must also come from the server's own origin: the ``Origin``
host and port must equal the ``Host`` header. Native dev clients send no
``Origin``.
Dev-client protocol (JSON objects, one per text frame):
- client -> server ``hello``: ``{"type": "hello", "platform", "device",
"app", "files": {path: sha256}}`` describing what the client already
holds in its overlay.
- server -> client ``sync``: ``{"type": "sync", "version", "entry",
"files": [{"path", "sha256", "content", "encoding"}], "removed": [...]}``
bringing the client up to date. The same shape is sent as
``"update"`` whenever the watcher sees a change.
- client -> server ``log`` (``level``, ``text``), ``error`` (``phase``,
``text``), ``reloaded`` (``version``, ``mode``, ``modules``): streamed
to the terminal.
"""
from
__future__
import
annotations
import
asyncio
import
base64
import
json
import
mimetypes
import
os
import
socket
import
sys
import
threading
import
time
from
dataclasses
import
dataclass
,
field
from
typing
import
Any
,
AsyncIterator
,
Callable
,
Dict
,
List
,
Optional
,
Protocol
,
Sequence
from
urllib
.
parse
import
parse_qs
,
unquote
,
urlsplit
from
.
import
auth
,
ws
from
.
watcher
import
FileWatcher
,
SourceChange
,
SourceSnapshot
,
snapshot_sources
__all__
=
[
"DEFAULT_PORT"
,
"DevServer"
,
"PreviewChannel"
,
"PreviewPeer"
,
"ServerInfo"
,
"lan_addresses"
,
]
DEFAULT_PORT
=
8765
"""Default port for ``pn start`` / ``pn preview``."""
_MAX_HEAD
=
64
*
1024
_STATIC_DIR
=
os
.
path
.
join
(
os
.
path
.
dirname
(
os
.
path
.
abspath
(
__file__
)),
"static"
)
Logger
=
Callable
[[
str
],
None
]
def
lan_addresses
()
->
List
[
str
]:
"""Best-effort list of this machine's non-loopback IPv4 addresses.
Used to print a URL a physical device on the same Wi-Fi can reach.
"""
found
:
List
[
str
]
=
[]
try
:
probe
=
socket
.
socket
(
socket
.
AF_INET
,
socket
.
SOCK_DGRAM
)
try
:
# No packets are sent; connecting a UDP socket just selects
# the interface that routes to the internet.
probe
.
connect
((
"10.255.255.255"
,
1
))
found
.
append
(
probe
.
getsockname
()[
0
])
finally
:
probe
.
close
()
except
OSError
:
pass
try
:
for
info
in
socket
.
getaddrinfo
(
socket
.
gethostname
(),
None
,
socket
.
AF_INET
):
addr
=
str
(
info
[
4
][
0
])
if
not
addr
.
startswith
(
"127."
)
and
addr
not
in
found
:
found
.
append
(
addr
)
except
OSError
:
pass
return
found
@
dataclass
class
ServerInfo
:
"""What the server is serving and where."""
host
:
str
port
:
int
project_root
:
str
entry_module
:
str
project_name
:
str
=
""
token
:
str
=
field
(
default
=
""
,
repr
=
False
)
def
url
(
self
,
host
:
Optional
[
str
]
=
None
)
->
str
:
"""The HTTP base URL, substituting ``host`` for the bind address."""
return
f"http://
{
host
or
self
.
display_host
}
:
{
self
.
port
}
"
def
preview_url
(
self
,
host
:
Optional
[
str
]
=
None
)
->
str
:
"""The browser preview URL, carrying the dev token once."""
return
auth
.
with_token
(
self
.
url
(
host
)
+
"/"
,
self
.
token
)
def
ws_url
(
self
,
host
:
Optional
[
str
]
=
None
)
->
str
:
"""The dev-client WebSocket URL, including the dev token."""
return
auth
.
with_token
(
f"ws://
{
host
or
self
.
display_host
}
:
{
self
.
port
}
/ws?role=client"
,
self
.
token
)
@
property
def
display_host
(
self
)
->
str
:
"""A host suitable for a URL (``0.0.0.0`` becomes ``localhost``)."""
return
"localhost"
if
self
.
host
in
(
""
,
"0.0.0.0"
,
"::"
)
else
self
.
host
# ======================================================================
# Preview channel
# ======================================================================
class
PreviewPeer
:
"""A connected browser preview page; ``send`` is safe from any thread."""
def
__init__
(
self
,
server
:
"DevServer"
,
writer
:
asyncio
.
StreamWriter
)
->
None
:
self
.
_server
=
server
self
.
_writer
=
writer
self
.
closed
=
threading
.
Event
()
def
send
(
self
,
text
:
str
)
->
None
:
"""Queue one text frame to the page (dropped once the peer is closed)."""
if
self
.
closed
.
is_set
():
return
self
.
_server
.
_call_soon
(
self
.
_send_now
,
text
)
def
_send_now
(
self
,
text
:
str
)
->
None
:
if
self
.
closed
.
is_set
():
return
try
:
self
.
_writer
.
write
(
ws
.
encode_frame
(
ws
.
TEXT
,
text
.
encode
(
"utf-8"
)))
except
Exception
:
self
.
closed
.
set
()
def
close
(
self
)
->
None
:
"""Ask the server to close this page's socket."""
self
.
_server
.
_call_soon
(
self
.
_close_now
)
def
_close_now
(
self
)
->
None
:
if
self
.
closed
.
is_set
():
return
self
.
closed
.
set
()
try
:
self
.
_writer
.
write
(
ws
.
encode_close
())
self
.
_writer
.
close
()
except
Exception
:
pass
class
PreviewChannel
(
Protocol
):
"""What the preview installs to receive the page's bridge traffic.
Every method is called on the server thread; implementations hop
to their own thread as needed.
"""
def
on_preview_connected
(
self
,
peer
:
PreviewPeer
,
info
:
Dict
[
str
,
Any
])
->
None
:
"""A page connected (``info`` carries its query parameters)."""
def
on_preview_message
(
self
,
peer
:
PreviewPeer
,
text
:
str
)
->
None
:
"""A text frame arrived from the page."""
def
on_preview_disconnected
(
self
,
peer
:
PreviewPeer
)
->
None
:
"""The page went away."""
# ======================================================================
# Dev clients
# ======================================================================
@
dataclass
class
DevClient
:
"""One connected on-device dev client."""
id
:
int
writer
:
asyncio
.
StreamWriter
platform
:
str
=
"unknown"
device
:
str
=
""
app
:
str
=
""
connected_at
:
float
=
field
(
default_factory
=
time
.
time
)
files
:
Dict
[
str
,
str
]
=
field
(
default_factory
=
dict
)
def
label
(
self
)
->
str
:
"""A short human label for log lines."""
parts
=
[
self
.
platform
]
if
self
.
device
:
parts
.
append
(
self
.
device
)
return
" "
.
join
(
parts
)
# ======================================================================
# The server
# ======================================================================
class
DevServer
:
"""Serve sources, assets, and the live protocol for one project.
Args:
project_root: Directory containing ``app/`` and ``pythonnative.toml``.
entry_module: The app's entry module (``"app.main"``).
host: Bind address. ``0.0.0.0`` so devices on the LAN can reach
it; pass ``127.0.0.1`` to stay local.
port: TCP port; ``0`` picks a free one.
project_name: Shown in the preview page and ``/status``.
token: The dev token clients must present; defaults to this
user's token from
[`load_token`][pythonnative.devserver.auth.load_token].
static_dir: Where the preview page's assets live.
log: Where to print client logs and connection events.
watch: Whether to run the file watcher.
"""
def
__init__
(
self
,
project_root
:
str
,
entry_module
:
str
=
"app.main"
,
*
,
host
:
str
=
"0.0.0.0"
,
port
:
int
=
DEFAULT_PORT
,
project_name
:
str
=
""
,
token
:
Optional
[
str
]
=
None
,
static_dir
:
Optional
[
str
]
=
None
,
log
:
Optional
[
Logger
]
=
None
,
watch
:
bool
=
True
,
)
->
None
:
self
.
project_root
=
os
.
path
.
abspath
(
project_root
)
self
.
token
=
token
or
auth
.
load_token
()
self
.
entry_module
=
entry_module
self
.
project_name
=
project_name
self
.
static_dir
=
static_dir
or
_STATIC_DIR
self
.
log
:
Logger
=
log
or
(
lambda
line
:
print
(
line
,
file
=
sys
.
stderr
,
flush
=
True
))
self
.
_host
=
host
self
.
_port
=
port
self
.
_watch
=
watch
self
.
_loop
:
Optional
[
asyncio
.
AbstractEventLoop
]
=
None
self
.
_thread
:
Optional
[
threading
.
Thread
]
=
None
self
.
_server
:
Optional
[
asyncio
.
base_events
.
Server
]
=
None
self
.
_started
=
threading
.
Event
()
self
.
_start_error
:
Optional
[
BaseException
]
=
None
self
.
_clients
:
Dict
[
int
,
DevClient
]
=
{}
self
.
_client_ids
=
0
self
.
_preview
:
Optional
[
PreviewChannel
]
=
None
self
.
_preview_peer
:
Optional
[
PreviewPeer
]
=
None
self
.
_watcher
:
Optional
[
FileWatcher
]
=
None
self
.
_snapshot
:
SourceSnapshot
=
snapshot_sources
(
self
.
project_root
)
self
.
_snapshot_lock
=
threading
.
Lock
()
self
.
_change_listeners
:
List
[
Callable
[[
SourceChange
,
SourceSnapshot
],
None
]]
=
[]
self
.
info
=
ServerInfo
(
host
=
host
,
port
=
port
,
project_root
=
self
.
project_root
,
entry_module
=
entry_module
,
project_name
=
project_name
,
token
=
self
.
token
,
)
# -- lifecycle -------------------------------------------------------
def
start
(
self
)
->
ServerInfo
:
"""Bind the socket on a background thread and return the address.
Raises:
OSError: When the port is taken (the CLI prints a hint).
"""
if
self
.
_thread
is
not
None
:
return
self
.
info
self
.
_thread
=
threading
.
Thread
(
target
=
self
.
_run
,
name
=
"pn-dev-server"
,
daemon
=
True
)
self
.
_thread
.
start
()
self
.
_started
.
wait
(
timeout
=
10.0
)
if
self
.
_start_error
is
not
None
:
error
,
self
.
_start_error
=
self
.
_start_error
,
None
self
.
_thread
=
None
raise
error
if
self
.
_watch
:
self
.
_watcher
=
FileWatcher
(
self
.
project_root
,
self
.
_on_files_changed
)
with
self
.
_snapshot_lock
:
self
.
_snapshot
=
self
.
_watcher
.
snapshot
self
.
_watcher
.
start
()
return
self
.
info
def
stop
(
self
)
->
None
:
"""Close every connection and stop the thread."""
watcher
,
self
.
_watcher
=
self
.
_watcher
,
None
if
watcher
is
not
None
:
watcher
.
stop
()
loop
=
self
.
_loop
if
loop
is
not
None
and
not
loop
.
is_closed
():
loop
.
call_soon_threadsafe
(
self
.
_shutdown
)
thread
,
self
.
_thread
=
self
.
_thread
,
None
if
thread
is
not
None
:
thread
.
join
(
timeout
=
5.0
)
def
_run
(
self
)
->
None
:
loop
=
asyncio
.
new_event_loop
()
self
.
_loop
=
loop
asyncio
.
set_event_loop
(
loop
)
try
:
server
=
loop
.
run_until_complete
(
asyncio
.
start_server
(
self
.
_handle_connection
,
self
.
_host
,
self
.
_port
))
except
BaseException
as
exc
:
self
.
_start_error
=
exc
self
.
_started
.
set
()
loop
.
close
()
return
self
.
_server
=
server
sockets
:
Sequence
[
Any
]
=
server
.
sockets
or
[]
if
sockets
:
self
.
info
.
port
=
int
(
sockets
[
0
].
getsockname
()[
1
])
self
.
_started
.
set
()
try
:
loop
.
run_forever
()
finally
:
try
:
loop
.
run_until_complete
(
loop
.
shutdown_asyncgens
())
except
Exception
:
pass
loop
.
close
()
def
_shutdown
(
self
)
->
None
:
loop
=
self
.
_loop
if
self
.
_server
is
not
None
:
self
.
_server
.
close
()
for
client
in
list
(
self
.
_clients
.
values
()):
try
:
client
.
writer
.
write
(
ws
.
encode_close
())
client
.
writer
.
close
()
except
Exception
:
pass
self
.
_clients
.
clear
()
if
self
.
_preview_peer
is
not
None
:
self
.
_preview_peer
.
_close_now
()
if
loop
is
not
None
:
loop
.
call_soon
(
loop
.
stop
)
def
_call_soon
(
self
,
fn
:
Callable
[...,
Any
],
*
args
:
Any
)
->
None
:
loop
=
self
.
_loop
if
loop
is
None
or
loop
.
is_closed
():
return
try
:
loop
.
call_soon_threadsafe
(
fn
,
*
args
)
except
RuntimeError
:
pass
# -- state -----------------------------------------------------------
@
property
def
snapshot
(
self
)
->
SourceSnapshot
:
"""The current source snapshot."""
with
self
.
_snapshot_lock
:
return
self
.
_snapshot
@
property
def
clients
(
self
)
->
List
[
DevClient
]:
"""Connected dev clients (a copy)."""
return
list
(
self
.
_clients
.
values
())
def
set_preview_channel
(
self
,
channel
:
Optional
[
PreviewChannel
])
->
None
:
"""Install the handler for the browser preview's bridge traffic."""
self
.
_preview
=
channel
def
add_change_listener
(
self
,
listener
:
Callable
[[
SourceChange
,
SourceSnapshot
],
None
])
->
Callable
[[],
None
]:
"""Be told (on the watcher thread) when sources change; returns an unsubscribe."""
self
.
_change_listeners
.
append
(
listener
)
def
_remove
()
->
None
:
try
:
self
.
_change_listeners
.
remove
(
listener
)
except
ValueError
:
pass
return
_remove
def
manifest
(
self
)
->
Dict
[
str
,
Any
]:
"""The ``/manifest`` document."""
snap
=
self
.
snapshot
return
{
"version"
:
snap
.
version
,
"entry"
:
self
.
entry_module
,
"files"
:
dict
(
snap
.
files
)}
def
status
(
self
)
->
Dict
[
str
,
Any
]:
"""The ``/status`` document."""
snap
=
self
.
snapshot
return
{
"name"
:
self
.
project_name
,
"entry"
:
self
.
entry_module
,
"project_root"
:
self
.
project_root
,
"version"
:
snap
.
version
,
"file_count"
:
len
(
snap
.
files
),
"clients"
: [
{
"id"
:
c
.
id
,
"platform"
:
c
.
platform
,
"device"
:
c
.
device
,
"app"
:
c
.
app
,
"connected_at"
:
c
.
connected_at
}
for
c
in
self
.
_clients
.
values
()
],
"preview_connected"
:
self
.
_preview_peer
is
not
None
and
not
self
.
_preview_peer
.
closed
.
is_set
(),
"lan"
:
lan_addresses
(),
"port"
:
self
.
info
.
port
,
}
# -- file changes ----------------------------------------------------
def
_on_files_changed
(
self
,
change
:
SourceChange
,
snapshot
:
SourceSnapshot
)
->
None
:
with
self
.
_snapshot_lock
:
self
.
_snapshot
=
snapshot
summary
=
", "
.
join
(
change
.
changed
+
[
f"-
{
p
}
"
for
p
in
change
.
removed
])
self
.
log
(
f"[pn] changed:
{
summary
}
"
)
for
listener
in
list
(
self
.
_change_listeners
):
try
:
listener
(
change
,
snapshot
)
except
Exception
as
exc
:
self
.
log
(
f"[pn] change listener failed:
{
exc
!r
}
"
)
if
self
.
_clients
:
message
=
self
.
_sync_message
(
"update"
,
snapshot
,
change
.
changed
,
change
.
removed
)
self
.
_call_soon
(
self
.
_broadcast
,
message
)
def
_sync_message
(
self
,
kind
:
str
,
snapshot
:
SourceSnapshot
,
paths
:
Sequence
[
str
],
removed
:
Sequence
[
str
])
->
str
:
files
:
List
[
Dict
[
str
,
Any
]]
=
[]
for
path
in
paths
:
data
=
snapshot
.
read
(
path
)
if
data
is
None
:
continue
files
.
append
(
_encode_file
(
path
,
snapshot
.
files
.
get
(
path
,
""
),
data
))
return
json
.
dumps
(
{
"type"
:
kind
,
"version"
:
snapshot
.
version
,
"entry"
:
self
.
entry_module
,
"files"
:
files
,
"removed"
:
list
(
removed
),
}
)
def
_broadcast
(
self
,
message
:
str
)
->
None
:
frame
=
ws
.
encode_frame
(
ws
.
TEXT
,
message
.
encode
(
"utf-8"
))
for
client
in
list
(
self
.
_clients
.
values
()):
try
:
client
.
writer
.
write
(
frame
)
except
Exception
:
self
.
_drop_client
(
client
)
def
_drop_client
(
self
,
client
:
DevClient
)
->
None
:
if
self
.
_clients
.
pop
(
client
.
id
,
None
)
is
not
None
:
self
.
log
(
f"[pn]
{
client
.
label
()
}
disconnected"
)
try
:
client
.
writer
.
close
()
except
Exception
:
pass
# -- connections -----------------------------------------------------
async
def
_handle_connection
(
self
,
reader
:
asyncio
.
StreamReader
,
writer
:
asyncio
.
StreamWriter
)
->
None
:
try
:
head
=
await
reader
.
readuntil
(
b"
\r
\n
\r
\n
"
)
except
(
asyncio
.
IncompleteReadError
,
asyncio
.
LimitOverrunError
,
ConnectionError
):
writer
.
close
()
return
if
len
(
head
)
>
_MAX_HEAD
:
writer
.
close
()
return
start_line
,
headers
=
ws
.
parse_http_headers
(
head
)
parts
=
start_line
.
split
()
if
len
(
parts
)
<
2
:
writer
.
close
()
return
method
,
target
=
parts
[
0
],
parts
[
1
]
url
=
urlsplit
(
target
)
path
=
unquote
(
url
.
path
)
query
=
{
k
:
v
[
-
1
]
for
k
,
v
in
parse_qs
(
url
.
query
).
items
()}
if
"websocket"
in
headers
.
get
(
"upgrade"
,
""
).
lower
():
await
self
.
_serve_websocket
(
reader
,
writer
,
headers
,
path
,
query
)
return
try
:
await
self
.
_serve_http
(
writer
,
method
,
path
,
query
,
headers
)
finally
:
try
:
writer
.
close
()
except
Exception
:
pass
def
_check_token
(
self
,
headers
:
Dict
[
str
,
str
],
query
:
Dict
[
str
,
str
])
->
int
:
"""``200`` for a valid token, ``401`` when none was presented, ``403`` for a wrong one."""
presented
=
auth
.
request_token
(
headers
,
query
)
if
presented
is
None
:
return
401
return
200
if
auth
.
token_matches
(
presented
,
self
.
token
)
else
403
async
def
_serve_http
(
self
,
writer
:
asyncio
.
StreamWriter
,
method
:
str
,
path
:
str
,
query
:
Dict
[
str
,
str
],
headers
:
Dict
[
str
,
str
]
)
->
None
:
if
method
not
in
(
"GET"
,
"HEAD"
):
_respond
(
writer
,
405
,
b"method not allowed"
,
"text/plain"
)
return
if
path
in
(
"/"
,
"/index.html"
):
if
auth
.
QUERY_PARAM
in
query
:
# Trade the URL's token for a cookie, then drop it from the address bar.
if
not
auth
.
token_matches
(
query
[
auth
.
QUERY_PARAM
],
self
.
token
):
_respond_refusal
(
writer
,
403
)
return
cookie
=
f"
{
auth
.
COOKIE_NAME
}
=
{
self
.
token
}
; HttpOnly; SameSite=Strict; Path=/"
_respond
(
writer
,
302
,
b""
,
"text/plain"
,
headers
=
{
"Location"
:
"/"
,
"Set-Cookie"
:
cookie
})
return
_respond_file
(
writer
,
os
.
path
.
join
(
self
.
static_dir
,
"index.html"
))
return
if
path
==
"/static/schema.js"
:
from
..
sdk
.
schema
import
manifest
_respond
(
writer
,
200
, (
"export default "
+
json
.
dumps
(
manifest
(),
default
=
str
)
+
";"
).
encode
(),
"text/javascript"
)
return
if
path
.
startswith
(
"/static/"
):
name
=
path
[
len
(
"/static/"
) :]
root
=
os
.
path
.
realpath
(
self
.
static_dir
)
candidate
=
os
.
path
.
realpath
(
os
.
path
.
join
(
root
,
name
))
if
(
not
name
or
any
(
part
.
startswith
(
"."
)
for
part
in
name
.
split
(
"/"
))
or
os
.
path
.
commonpath
([
root
,
candidate
])
!=
root
):
_respond
(
writer
,
404
,
b"not found"
,
"text/plain"
)
return
_respond_file
(
writer
,
candidate
)
return
# Everything past the page and its static files needs the token,
# including routes that don't exist (so they reveal nothing).
status
=
self
.
_check_token
(
headers
,
query
)
if
status
!=
200
:
_respond_refusal
(
writer
,
status
)
return
if
path
==
"/manifest"
:
_respond_json
(
writer
,
self
.
manifest
())
return
if
path
==
"/status"
:
_respond_json
(
writer
,
self
.
status
())
return
if
path
.
startswith
(
"/file/"
):
rel
=
path
[
len
(
"/file/"
) :]
snap
=
self
.
snapshot
if
rel
not
in
snap
.
files
:
_respond
(
writer
,
404
,
b"not found"
,
"text/plain"
)
return
data
=
snap
.
read
(
rel
)
if
data
is
None
:
_respond
(
writer
,
404
,
b"not found"
,
"text/plain"
)
return
_respond
(
writer
,
200
,
data
,
mimetypes
.
guess_type
(
rel
)[
0
]
or
"application/octet-stream"
)
return
if
path
.
startswith
(
"/assets/"
):
self
.
_serve_asset
(
writer
,
path
[
len
(
"/assets/"
) :])
return
_respond
(
writer
,
404
,
b"not found"
,
"text/plain"
)
def
_serve_asset
(
self
,
writer
:
asyncio
.
StreamWriter
,
rel
:
str
)
->
None
:
"""Serve ``app/assets/<rel>``, the manifest, or the generated font CSS.
The browser preview resolves ``asset://`` URIs against this
route: ``/assets/pn_assets.json`` is the
[`AssetManifest`][pythonnative.assets.AssetManifest] of the
current tree, ``/assets/fonts.css`` declares one ``@font-face``
per bundled font so ``font_family`` names work in the page, and
anything else is the file itself.
"""
from
..
import
assets
as
assets_module
root
=
os
.
path
.
join
(
self
.
snapshot
.
root
,
"app"
,
assets_module
.
ASSETS_DIR
)
if
rel
==
assets_module
.
MANIFEST_NAME
:
_respond_json
(
writer
,
assets_module
.
scan
(
root
).
to_dict
())
return
if
rel
==
"fonts.css"
:
css
=
"
\n
"
.
join
(
"@font-face {
\n
"
f' font-family: "
{
face
.
family
}
";
\n
'
f" font-weight:
{
face
.
weight
}
;
\n
"
f" font-style:
{
'italic'
if
face
.
italic
else
'normal'
}
;
\n
"
f' src: url("/assets/
{
face
.
path
}
");
\n
'
"}"
for
face
in
assets_module
.
scan
(
root
).
fonts
)
_respond
(
writer
,
200
,
css
.
encode
(
"utf-8"
),
"text/css; charset=utf-8"
)
return
try
:
normalized
=
assets_module
.
normalize_path
(
unquote
(
rel
))
except
ValueError
:
_respond
(
writer
,
404
,
b"not found"
,
"text/plain"
)
return
snap
=
self
.
snapshot
key
=
f"app/
{
assets_module
.
ASSETS_DIR
}
/
{
normalized
}
"
data
=
snap
.
read
(
key
)
if
key
in
snap
.
files
else
None
if
data
is
None
:
_respond
(
writer
,
404
,
b"not found"
,
"text/plain"
)
return
_respond
(
writer
,
200
,
data
,
mimetypes
.
guess_type
(
normalized
)[
0
]
or
"application/octet-stream"
)
async
def
_serve_websocket
(
self
,
reader
:
asyncio
.
StreamReader
,
writer
:
asyncio
.
StreamWriter
,
headers
:
Dict
[
str
,
str
],
path
:
str
,
query
:
Dict
[
str
,
str
],
)
->
None
:
# Refuse with a plain HTTP response before upgrading, so a rejected
# peer never gets a socket.
refusal
:
Optional
[
int
]
=
None
if
path
!=
"/ws"
:
refusal
=
404
elif
not
_same_origin
(
headers
):
refusal
=
403
else
:
status
=
self
.
_check_token
(
headers
,
query
)
refusal
=
None
if
status
==
200
else
status
if
refusal
is
not
None
:
_respond_refusal
(
writer
,
refusal
)
try
:
await
writer
.
drain
()
except
ConnectionError
:
pass
writer
.
close
()
return
try
:
writer
.
write
(
ws
.
server_handshake
(
headers
))
await
writer
.
drain
()
except
(
ws
.
HandshakeError
,
ConnectionError
):
writer
.
close
()
return
role
=
query
.
get
(
"role"
,
"client"
)
if
role
==
"preview"
:
await
self
.
_preview_session
(
reader
,
writer
,
query
)
else
:
await
self
.
_client_session
(
reader
,
writer
)
async
def
_read_messages
(
self
,
reader
:
asyncio
.
StreamReader
,
writer
:
asyncio
.
StreamWriter
)
->
AsyncIterator
[
str
]:
"""Yield text messages until the peer closes; answers pings."""
decoder
=
ws
.
FrameDecoder
()
while
True
:
try
:
chunk
=
await
reader
.
read
(
65536
)
except
(
ConnectionError
,
asyncio
.
CancelledError
,
OSError
):
return
if
not
chunk
:
return
try
:
messages
=
list
(
decoder
.
feed
(
chunk
))
except
ws
.
WebSocketError
:
try
:
writer
.
write
(
ws
.
encode_close
(
1002
,
"protocol error"
))
except
Exception
:
pass
return
for
opcode
,
payload
in
messages
:
if
opcode
==
ws
.
TEXT
:
try
:
yield
payload
.
decode
(
"utf-8"
)
except
UnicodeDecodeError
:
continue
elif
opcode
==
ws
.
PING
:
writer
.
write
(
ws
.
encode_frame
(
ws
.
PONG
,
payload
))
elif
opcode
==
ws
.
CLOSE
:
try
:
writer
.
write
(
ws
.
encode_close
())
except
Exception
:
pass
return
async
def
_client_session
(
self
,
reader
:
asyncio
.
StreamReader
,
writer
:
asyncio
.
StreamWriter
)
->
None
:
self
.
_client_ids
+=
1
client
=
DevClient
(
id
=
self
.
_client_ids
,
writer
=
writer
)
self
.
_clients
[
client
.
id
]
=
client
try
:
async
for
text
in
self
.
_read_messages
(
reader
,
writer
):
try
:
message
=
json
.
loads
(
text
)
except
ValueError
:
continue
if
isinstance
(
message
,
dict
):
self
.
_on_client_message
(
client
,
message
)
finally
:
self
.
_drop_client
(
client
)
def
_on_client_message
(
self
,
client
:
DevClient
,
message
:
Dict
[
str
,
Any
])
->
None
:
kind
=
message
.
get
(
"type"
)
if
kind
==
"hello"
:
client
.
platform
=
str
(
message
.
get
(
"platform"
)
or
"unknown"
)
client
.
device
=
str
(
message
.
get
(
"device"
)
or
""
)
client
.
app
=
str
(
message
.
get
(
"app"
)
or
""
)
files
=
message
.
get
(
"files"
)
client
.
files
=
{
str
(
k
):
str
(
v
)
for
k
,
v
in
files
.
items
()}
if
isinstance
(
files
,
dict
)
else
{}
self
.
log
(
f"[pn]
{
client
.
label
()
}
connected"
)
snap
=
self
.
snapshot
changed
=
sorted
(
p
for
p
,
digest
in
snap
.
files
.
items
()
if
client
.
files
.
get
(
p
)
!=
digest
)
removed
=
sorted
(
p
for
p
in
client
.
files
if
p
not
in
snap
.
files
)
try
:
client
.
writer
.
write
(
ws
.
encode_frame
(
ws
.
TEXT
,
self
.
_sync_message
(
"sync"
,
snap
,
changed
,
removed
).
encode
(
"utf-8"
))
)
except
Exception
:
self
.
_drop_client
(
client
)
return
if
kind
==
"log"
:
level
=
str
(
message
.
get
(
"level"
)
or
"info"
)
text
=
str
(
message
.
get
(
"text"
)
or
""
).
rstrip
(
"
\n
"
)
prefix
=
f"[
{
client
.
label
()
}
]"
if
level
in
(
"error"
,
"warn"
,
"warning"
):
prefix
=
f"[
{
client
.
label
()
}
{
level
}
]"
for
line
in
text
.
split
(
"
\n
"
):
self
.
log
(
f"
{
prefix
}
{
line
}
"
)
return
if
kind
==
"error"
:
phase
=
str
(
message
.
get
(
"phase"
)
or
"runtime"
)
text
=
str
(
message
.
get
(
"text"
)
or
""
).
rstrip
(
"
\n
"
)
self
.
log
(
f"[
{
client
.
label
()
}
] error during
{
phase
}
:"
)
for
line
in
text
.
split
(
"
\n
"
):
self
.
log
(
f"
{
line
}
"
)
return
if
kind
==
"reloaded"
:
mode
=
str
(
message
.
get
(
"mode"
)
or
"reload"
)
modules
=
message
.
get
(
"modules"
)
or
[]
what
=
", "
.
join
(
str
(
m
)
for
m
in
modules
)
if
isinstance
(
modules
,
list
)
and
modules
else
"app"
self
.
log
(
f"[
{
client
.
label
()
}
]
{
mode
}
:
{
what
}
"
)
return
async
def
_preview_session
(
self
,
reader
:
asyncio
.
StreamReader
,
writer
:
asyncio
.
StreamWriter
,
query
:
Dict
[
str
,
str
]
)
->
None
:
channel
=
self
.
_preview
if
channel
is
None
:
writer
.
write
(
ws
.
encode_close
(
1013
,
"no preview running"
))
writer
.
close
()
return
previous
=
self
.
_preview_peer
if
previous
is
not
None
and
not
previous
.
closed
.
is_set
():
# One page at a time: the newest tab takes over the app.
try
:
previous
.
_send_now
(
json
.
dumps
([
"dev"
, {
"type"
:
"superseded"
}]))
except
Exception
:
pass
previous
.
_close_now
()
channel
.
on_preview_disconnected
(
previous
)
peer
=
PreviewPeer
(
self
,
writer
)
self
.
_preview_peer
=
peer
channel
.
on_preview_connected
(
peer
,
dict
(
query
))
try
:
async
for
text
in
self
.
_read_messages
(
reader
,
writer
):
channel
.
on_preview_message
(
peer
,
text
)
finally
:
peer
.
closed
.
set
()
if
self
.
_preview_peer
is
peer
:
self
.
_preview_peer
=
None
channel
.
on_preview_disconnected
(
peer
)
try
:
writer
.
close
()
except
Exception
:
pass
# ======================================================================
# HTTP helpers
# ======================================================================
def
_encode_file
(
path
:
str
,
digest
:
str
,
data
:
bytes
)
->
Dict
[
str
,
Any
]:
try
:
return
{
"path"
:
path
,
"sha256"
:
digest
,
"content"
:
data
.
decode
(
"utf-8"
),
"encoding"
:
"utf8"
}
except
UnicodeDecodeError
:
return
{
"path"
:
path
,
"sha256"
:
digest
,
"content"
:
base64
.
b64encode
(
data
).
decode
(
"ascii"
),
"encoding"
:
"base64"
}
_STATUS_TEXT
=
{
200
:
"OK"
,
302
:
"Found"
,
401
:
"Unauthorized"
,
403
:
"Forbidden"
,
404
:
"Not Found"
,
405
:
"Method Not Allowed"
,
500
:
"Internal Server Error"
,
}
_REFUSALS
:
Dict
[
int
,
bytes
]
=
{
401
:
b"This dev server needs its token. Open the URL that `pn start` printed.
\n
"
,
403
:
b"Forbidden: wrong dev token or a cross-origin request. Open the URL that `pn start` printed.
\n
"
,
404
:
b"not found"
,
}
def
_same_origin
(
headers
:
Dict
[
str
,
str
])
->
bool
:
"""Whether a WebSocket upgrade may proceed given its ``Origin``.
Browsers always send ``Origin`` on a WebSocket upgrade, and any page
can open a socket to any host, so a browser peer must come from this
server's own origin: the ``Origin`` host and port must equal the
``Host`` header. Native dev clients send no ``Origin`` and pass.
"""
origin
=
headers
.
get
(
"origin"
)
if
origin
is
None
:
return
True
host
=
headers
.
get
(
"host"
,
""
).
strip
().
lower
()
try
:
netloc
=
urlsplit
(
origin
.
strip
()).
netloc
.
lower
()
except
ValueError
:
return
False
return
bool
(
host
)
and
netloc
==
host
def
_respond_refusal
(
writer
:
asyncio
.
StreamWriter
,
status
:
int
)
->
None
:
_respond
(
writer
,
status
,
_REFUSALS
.
get
(
status
,
b""
),
"text/plain; charset=utf-8"
)
def
_respond
(
writer
:
asyncio
.
StreamWriter
,
status
:
int
,
body
:
bytes
,
content_type
:
str
,
*
,
headers
:
Optional
[
Dict
[
str
,
str
]]
=
None
,
)
->
None
:
extra
=
""
.
join
(
f"
{
name
}
:
{
value
}
\r
\n
"
for
name
,
value
in
(
headers
or
{}).
items
())
head
=
(
f"HTTP/1.1
{
status
}
{
_STATUS_TEXT
.
get
(
status
,
'OK'
)
}
\r
\n
"
f"Content-Type:
{
content_type
}
\r
\n
"
f"Content-Length:
{
len
(
body
)
}
\r
\n
"
"Cache-Control: no-store
\r
\n
"
f"
{
extra
}
"
"Connection: close
\r
\n
"
"
\r
\n
"
).
encode
(
"ascii"
)
try
:
writer
.
write
(
head
+
body
)
except
Exception
:
pass
def
_respond_json
(
writer
:
asyncio
.
StreamWriter
,
document
:
Any
)
->
None
:
_respond
(
writer
,
200
,
json
.
dumps
(
document
).
encode
(
"utf-8"
),
"application/json; charset=utf-8"
)
def
_respond_file
(
writer
:
asyncio
.
StreamWriter
,
path
:
str
)
->
None
:
try
:
with
open
(
path
,
"rb"
)
as
handle
:
data
=
handle
.
read
()
except
OSError
:
_respond
(
writer
,
404
,
b"not found"
,
"text/plain"
)
return
content_type
=
mimetypes
.
guess_type
(
path
)[
0
]
or
"application/octet-stream"
if
path
.
endswith
(
".js"
):
content_type
=
"text/javascript"
if
content_type
.
startswith
(
"text/"
)
and
"charset"
not
in
content_type
:
content_type
+=
"; charset=utf-8"
_respond
(
writer
,
200
,
data
,
content_type
)
Back
|
FazBrowse Home
|
New Git URL