bs-simulators 0.1.3__tar.gz → 0.1.4__tar.gz

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.
Files changed (70) hide show
  1. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/PKG-INFO +1 -1
  2. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/docs/http.md +15 -1
  3. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/pyproject.toml +1 -1
  4. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/src/bs_simulators/__init__.py +1 -1
  5. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/src/bs_simulators/comms/http/app.py +3 -2
  6. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/src/bs_simulators/comms/http/middleware.py +35 -3
  7. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/src/bs_simulators/comms/http/server.py +12 -6
  8. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/tests/test_simulation_adapters.py +55 -9
  9. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/.python-version +0 -0
  10. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/.readthedocs.yaml +0 -0
  11. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/AGENTS.md +0 -0
  12. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/LICENSE +0 -0
  13. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/LICENSE.benchmark-systems +0 -0
  14. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/README.md +0 -0
  15. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/docs/_static/architecture/configuration-access.svg +0 -0
  16. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/docs/_static/architecture/functional-core.svg +0 -0
  17. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/docs/_static/architecture/runtime-sequence.svg +0 -0
  18. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/docs/api.md +0 -0
  19. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/docs/architecture.md +0 -0
  20. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/docs/catalogue.md +0 -0
  21. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/docs/common-pitfalls.md +0 -0
  22. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/docs/conf.py +0 -0
  23. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/docs/development.md +0 -0
  24. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/docs/index.md +0 -0
  25. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/docs/installation.md +0 -0
  26. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/docs/pendulum.md +0 -0
  27. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/docs/recording.md +0 -0
  28. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/docs/requirements.txt +0 -0
  29. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/docs/simulation.md +0 -0
  30. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/examples/pendulum_core.ipynb +0 -0
  31. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/examples/pendulum_signal_adapter.py +0 -0
  32. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/examples/pendulum_sil_controller.py +0 -0
  33. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/examples/pendulum_sil_replay.py +0 -0
  34. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/src/bs_simulators/__main__.py +0 -0
  35. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/src/bs_simulators/catalogue/__init__.py +0 -0
  36. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/src/bs_simulators/catalogue/_validation.py +0 -0
  37. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/src/bs_simulators/catalogue/dc-motor.toml +0 -0
  38. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/src/bs_simulators/catalogue/johansson.toml +0 -0
  39. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/src/bs_simulators/catalogue/neutralization.toml +0 -0
  40. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/src/bs_simulators/catalogue/pendulum.toml +0 -0
  41. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/src/bs_simulators/cli/__init__.py +0 -0
  42. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/src/bs_simulators/cli/commands.py +0 -0
  43. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/src/bs_simulators/cli/configuration.py +0 -0
  44. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/src/bs_simulators/cli/execution.py +0 -0
  45. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/src/bs_simulators/cli/presentation.py +0 -0
  46. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/src/bs_simulators/comms/__init__.py +0 -0
  47. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/src/bs_simulators/comms/adapters.py +0 -0
  48. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/src/bs_simulators/comms/http/__init__.py +0 -0
  49. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/src/bs_simulators/runtime/__init__.py +0 -0
  50. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/src/bs_simulators/runtime/_validation.py +0 -0
  51. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/src/bs_simulators/runtime/core.py +0 -0
  52. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/src/bs_simulators/runtime/protocols.py +0 -0
  53. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/src/bs_simulators/runtime/signals.py +0 -0
  54. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/src/bs_simulators/runtime/steppers.py +0 -0
  55. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/src/bs_simulators/viewers/__init__.py +0 -0
  56. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/src/bs_simulators/viewers/dc-motor.html +0 -0
  57. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/src/bs_simulators/viewers/johansson.html +0 -0
  58. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/src/bs_simulators/viewers/neutralization.html +0 -0
  59. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/src/bs_simulators/viewers/pendulum.html +0 -0
  60. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/src/bs_simulators/viewers/scenes.js +0 -0
  61. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/src/bs_simulators/viewers/viewer.css +0 -0
  62. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/src/bs_simulators/viewers/viewer.js +0 -0
  63. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/tests/test_bundled_experiments.py +0 -0
  64. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/tests/test_catalogue.py +0 -0
  65. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/tests/test_cli.py +0 -0
  66. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/tests/test_dae_failure.py +0 -0
  67. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/tests/test_distribution.py +0 -0
  68. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/tests/test_generic_simulation.py +0 -0
  69. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/tests/test_simulation.py +0 -0
  70. {bs_simulators-0.1.3 → bs_simulators-0.1.4}/tests/viewer_scales.test.mjs +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: bs-simulators
3
- Version: 0.1.3
3
+ Version: 0.1.4
4
4
  Summary: Live simulators and transport adapters for benchmark-systems models
5
5
  License: MIT
6
6
  Requires-Python: >=3.13
@@ -131,9 +131,11 @@ lines with the following cell. Use a free port in the Colab runtime.
131
131
 
132
132
  ```python
133
133
  from google.colab import output
134
+ from urllib.parse import urlsplit
134
135
 
135
136
  port = 8766
136
- proxy_origin = output.eval_js(f"google.colab.kernel.proxyPort({port})")
137
+ proxy_url = urlsplit(output.eval_js(f"google.colab.kernel.proxyPort({port})"))
138
+ proxy_origin = f"{proxy_url.scheme}://{proxy_url.netloc}"
137
139
  server = create_server(simulation, port=port, colab_origin=proxy_origin)
138
140
  server_thread = threading.Thread(target=server.serve_forever, daemon=True)
139
141
  server_thread.start()
@@ -141,7 +143,19 @@ simulation.start()
141
143
  output.serve_kernel_port_as_iframe(port, height=650)
142
144
  ```
143
145
 
146
+ For recognized Colab proxy URLs, the read-only listener also accepts the
147
+ forwarded hostname for the same runtime. If the iframe returns
148
+ `invalid local Host` with another URL format, add
149
+ `colab_upstream_host="runtime.example.internal:8007"` to `create_server()`,
150
+ using the exact forwarded hostname and port observed in the current
151
+ session. Keep the public HTTPS origin in `colab_origin`. Both settings
152
+ apply to the read-only listener.
153
+
144
154
  The iframe can read the simulation and render the scene. If an HTTP SIL
145
155
  controller runs in the same runtime, start a separate default server on
146
156
  another loopback port and point the controller there. Use the shutdown
147
157
  sequence above for each server you start.
158
+
159
+ Before rerunning the startup cell, stop the current simulation, call
160
+ `server.server_close()` and join the server thread. The next run can use
161
+ the same port.
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "bs-simulators"
3
- version = "0.1.3"
3
+ version = "0.1.4"
4
4
  description = "Live simulators and transport adapters for benchmark-systems models"
5
5
  requires-python = ">=3.13"
6
6
  readme = "README.md"
@@ -7,7 +7,7 @@ dependency.
7
7
 
8
8
  from importlib import import_module
9
9
 
10
- __version__ = '0.1.3'
10
+ __version__ = '0.1.4'
11
11
 
12
12
  __all__ = ['Simulation', 'Stepper', 'ODEStepper', 'DAEStepper',
13
13
  'InMemoryAdapter', 'SimulationPort',
@@ -60,12 +60,13 @@ _INPUT_ERROR_RESPONSES = {
60
60
  }
61
61
 
62
62
 
63
- def _build_app(adapter, *, viewer, port, colab_host):
63
+ def _build_app(adapter, *, viewer, port, colab_host, colab_upstream_host=None):
64
64
  """Configure the FastAPI routes for the simulation and its viewer."""
65
65
  read_only = colab_host is not None
66
66
  app = FastAPI(title='bs-simulators', docs_url=None if read_only else '/docs',
67
67
  redoc_url=None, openapi_url=None if read_only else '/openapi.json')
68
- _install_request_policy(app, port=port, colab_host=colab_host)
68
+ _install_request_policy(app, port=port, colab_host=colab_host,
69
+ colab_upstream_host=colab_upstream_host)
69
70
 
70
71
  @app.exception_handler(StarletteHTTPException)
71
72
  async def http_error(request, error):
@@ -1,12 +1,19 @@
1
1
  """Request validation for local control and read-only Colab viewers."""
2
2
 
3
3
  import asyncio
4
+ import re
4
5
  from urllib.parse import urlsplit
5
6
 
6
7
  from fastapi import Request
7
8
  from fastapi.responses import JSONResponse
8
9
 
9
10
 
11
+ _COLAB_PROXY_HOST = re.compile(
12
+ r'[0-9]{1,5}-(?P<runtime>m-[a-z0-9]+(?:-[a-z0-9]+)*)-(?P<zone>[a-z])'
13
+ r'\.(?P<region>[a-z]+(?:-[a-z]+)+[0-9]+)\.prod\.r\.colab\.dev'
14
+ )
15
+
16
+
10
17
  def _colab_host(origin):
11
18
  """Extract the exact authority from the HTTPS URL returned by Colab."""
12
19
  parsed = urlsplit(origin)
@@ -17,7 +24,23 @@ def _colab_host(origin):
17
24
  return parsed.netloc.lower()
18
25
 
19
26
 
20
- def _install_request_policy(app, *, port, colab_host):
27
+ def _colab_upstream_authority(host):
28
+ """Validate an exact hostname and optional port observed behind the Colab proxy."""
29
+ if not isinstance(host, str) or not re.fullmatch(r'[a-zA-Z0-9.-]+(?::[0-9]{1,5})?', host):
30
+ raise ValueError('colab_upstream_host must be an exact hostname with an optional port')
31
+ urlsplit(f'//{host}').port # Reject ports outside the permitted range.
32
+ return host.lower()
33
+
34
+
35
+ def _infer_colab_upstream_host(public_host):
36
+ """Derive the runtime hostname for the observed Colab proxy DNS format."""
37
+ match = _COLAB_PROXY_HOST.fullmatch(public_host)
38
+ if match is None:
39
+ return None
40
+ return '{runtime}.{region}-{zone}.c.codatalab-user-runtimes.internal'.format(**match.groupdict())
41
+
42
+
43
+ def _install_request_policy(app, *, port, colab_host, colab_upstream_host=None):
21
44
  """Apply host, origin, method and body rules to one listener."""
22
45
  read_only = colab_host is not None
23
46
  authorities = {f'127.0.0.1:{port}', f'localhost:{port}'}
@@ -25,13 +48,22 @@ def _install_request_policy(app, *, port, colab_host):
25
48
  authorities.update(('127.0.0.1', 'localhost'))
26
49
  if read_only:
27
50
  authorities.add(colab_host)
51
+ if colab_upstream_host is not None:
52
+ authorities.add(colab_upstream_host)
53
+ inferred_host = (_infer_colab_upstream_host(colab_host)
54
+ if read_only and colab_upstream_host is None else None)
28
55
 
29
56
  @app.middleware('http')
30
57
  async def check_request(request: Request, call_next):
31
58
  host = request.headers.get('host', '').lower()
32
59
  origin = request.headers.get('origin')
33
- expected_origin = f'https://{host}' if host == colab_host else f'http://{host}'
34
- if host not in authorities:
60
+ hostname, separator, port_text = host.partition(':')
61
+ matches_upstream = hostname == inferred_host and (
62
+ not separator or (re.fullmatch(r'[0-9]{1,5}', port_text) and 0 < int(port_text) <= 65535)
63
+ )
64
+ from_colab = host in (colab_host, colab_upstream_host) or matches_upstream
65
+ expected_origin = f'https://{colab_host}' if from_colab else f'http://{host}'
66
+ if host not in authorities and not matches_upstream:
35
67
  response = JSONResponse({'error': 'invalid local Host'}, status_code=403)
36
68
  elif origin is not None and origin.lower() != expected_origin:
37
69
  response = JSONResponse({'error': 'cross-origin requests are not allowed'}, status_code=403)
@@ -9,7 +9,7 @@ from ...runtime.protocols import SimulationPort
9
9
  from ...viewers import VIEWER_FILES
10
10
  from ..adapters import InMemoryAdapter
11
11
  from .app import _build_app
12
- from .middleware import _colab_host
12
+ from .middleware import _colab_host, _colab_upstream_authority
13
13
 
14
14
 
15
15
  class _HTTPServer:
@@ -52,13 +52,17 @@ class _HTTPServer:
52
52
 
53
53
  def create_server(
54
54
  simulation: SimulationPort, *, host='127.0.0.1', port=8765, viewer=None, colab_origin=None,
55
+ colab_upstream_host=None,
55
56
  ):
56
57
  """Return an unstarted loopback server for a simulation.
57
58
 
58
59
  The default server hosts the viewer, the HTTP API and interactive API
59
60
  documentation at /docs. Writes use the controller identity "http".
60
61
  Pass the HTTPS origin returned by Colab as colab_origin to open a
61
- read-only listener for the notebook iframe. Port 0 selects a free port.
62
+ read-only listener for the notebook iframe. The listener recognizes the
63
+ forwarded hostname for matching Colab runtime URLs. If the proxy uses a
64
+ different format, colab_upstream_host can set an exact forwarded authority.
65
+ Port 0 selects a free port.
62
66
  """
63
67
  if host not in ('127.0.0.1', 'localhost'):
64
68
  raise ValueError('the demo server must bind to loopback')
@@ -66,14 +70,16 @@ def create_server(
66
70
  if selected_viewer is not None and selected_viewer not in VIEWER_FILES:
67
71
  raise ValueError('unknown packaged viewer')
68
72
  colab_host = _colab_host(colab_origin) if colab_origin is not None else None
73
+ if colab_upstream_host is not None:
74
+ if colab_host is None:
75
+ raise ValueError('colab_upstream_host requires colab_origin')
76
+ colab_upstream_host = _colab_upstream_authority(colab_upstream_host)
69
77
  adapter = InMemoryAdapter(simulation, controller_id='http')
70
78
 
71
- listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
79
+ listener = socket.create_server(('127.0.0.1', port))
72
80
  try:
73
- listener.bind(('127.0.0.1', port))
74
- listener.listen()
75
81
  app = _build_app(adapter, viewer=selected_viewer, port=listener.getsockname()[1],
76
- colab_host=colab_host)
82
+ colab_host=colab_host, colab_upstream_host=colab_upstream_host)
77
83
  return _HTTPServer(app, listener)
78
84
  except BaseException:
79
85
  listener.close()
@@ -1,6 +1,7 @@
1
1
  """Transport-independent controller protocols and measurement acceptance tests."""
2
2
 
3
3
  import json
4
+ import socket
4
5
  import threading
5
6
  from types import SimpleNamespace
6
7
  from urllib.error import HTTPError
@@ -315,21 +316,35 @@ def test_http_uses_structural_port_instead_of_concrete_pendulum():
315
316
  worker.join(timeout=5)
316
317
 
317
318
 
318
- def test_colab_listener_serves_viewer_without_exposing_control():
319
+ @pytest.mark.parametrize('proxy_host,forwarded_host,override,rejected_host', [
320
+ ('notebook-port.example.test', 'runtime.internal:8007', 'runtime.internal:8007',
321
+ 'runtime.internal:8008'),
322
+ ('8766-m-s-ase1a6-notebook-a.asia-east1.prod.r.colab.dev',
323
+ 'm-s-ase1a6-notebook.asia-east1-a.c.codatalab-user-runtimes.internal:8007', None,
324
+ 'm-s-ase1a6-someone-else.asia-east1-a.c.codatalab-user-runtimes.internal:8007'),
325
+ ('8766-m-s-xyz-notebook-b.us-central1.prod.r.colab.dev',
326
+ 'm-s-xyz-notebook.us-central1-b.c.codatalab-user-runtimes.internal:8080', None,
327
+ 'm-s-xyz-notebook.us-central1-a.c.codatalab-user-runtimes.internal:8080'),
328
+ ])
329
+ def test_colab_listener_serves_viewer_without_exposing_control(
330
+ proxy_host, forwarded_host, override, rejected_host,
331
+ ):
319
332
  plant = _StructuralPlant()
320
- proxy_host = 'notebook-port.example.test'
321
333
  proxy_origin = f'https://{proxy_host}'
322
- server = create_server(plant, port=0, viewer='pendulum', colab_origin=proxy_origin)
334
+ forwarded_headers = {'Host': forwarded_host}
335
+ server = create_server(plant, port=0, viewer='pendulum', colab_origin=proxy_origin,
336
+ colab_upstream_host=override)
323
337
  worker = threading.Thread(target=server.serve_forever)
324
338
  worker.start()
325
339
  base = f'http://127.0.0.1:{server.server_port}'
326
340
  proxy_headers = {'Host': proxy_host, 'Origin': proxy_origin}
327
341
  try:
328
- for path in ('/', '/assets/viewer.js', '/api/state', '/api/signals'):
329
- with urlopen(Request(base + path, headers=proxy_headers), timeout=2) as response:
330
- assert response.status == 200
342
+ for headers in (proxy_headers, forwarded_headers, {**forwarded_headers, 'Origin': proxy_origin}):
343
+ for path in ('/', '/assets/viewer.js', '/api/state', '/api/signals'):
344
+ with urlopen(Request(base + path, headers=headers), timeout=2) as response:
345
+ assert response.status == 200
331
346
 
332
- for headers in (proxy_headers, {}):
347
+ for headers in (proxy_headers, forwarded_headers, {}):
333
348
  request = Request(base + '/api/input', data=b'{"u":[0.9]}',
334
349
  headers={**headers, 'Content-Type': 'application/json'})
335
350
  with pytest.raises(HTTPError) as rejected:
@@ -337,8 +352,8 @@ def test_colab_listener_serves_viewer_without_exposing_control():
337
352
  assert rejected.value.code == 405
338
353
  rejected.value.close()
339
354
 
340
- for headers in ({'Host': 'unexpected.example.test'},
341
- {**proxy_headers, 'Origin': 'https://unexpected.example.test'}):
355
+ for headers in ({'Host': rejected_host},
356
+ {**forwarded_headers, 'Origin': 'https://unexpected.example.test'}):
342
357
  with pytest.raises(HTTPError) as rejected:
343
358
  urlopen(Request(base + '/api/state', headers=headers), timeout=2)
344
359
  assert rejected.value.code == 403
@@ -350,6 +365,37 @@ def test_colab_listener_serves_viewer_without_exposing_control():
350
365
  worker.join(timeout=5)
351
366
 
352
367
 
368
+ def test_colab_viewer_can_restart_on_the_same_port_after_an_http_request():
369
+ plant = _StructuralPlant()
370
+ origin = 'https://notebook-port.example.test'
371
+ with create_server(plant, port=0, viewer='pendulum', colab_origin=origin) as server:
372
+ port = server.server_port
373
+ worker = threading.Thread(target=server.serve_forever)
374
+ worker.start()
375
+ try:
376
+ with socket.create_connection(('127.0.0.1', port), timeout=3) as connection:
377
+ connection.sendall(
378
+ b'GET / HTTP/1.1\r\nHost: notebook-port.example.test\r\nConnection: close\r\n\r\n'
379
+ )
380
+ with connection.makefile('rb') as response:
381
+ # Wait for the server to close first, leaving its side in TIME_WAIT.
382
+ assert response.read().startswith(b'HTTP/1.1 200 ')
383
+ finally:
384
+ server.server_close()
385
+ worker.join(timeout=5)
386
+
387
+ with create_server(plant, port=port, viewer='pendulum', colab_origin=origin) as restarted:
388
+ assert restarted.server_port == port
389
+
390
+
391
+ def test_colab_upstream_host_requires_a_read_only_listener():
392
+ with pytest.raises(ValueError, match='requires colab_origin'):
393
+ create_server(_StructuralPlant(), port=0, colab_upstream_host='runtime.internal:8007')
394
+ with pytest.raises(ValueError, match='exact hostname'):
395
+ create_server(_StructuralPlant(), port=0, colab_origin='https://notebook.example.test',
396
+ colab_upstream_host='*.internal')
397
+
398
+
353
399
  def test_http_cannot_spoof_the_active_controller():
354
400
  simulation = load_configuration('pendulum').create(active_controller='plc')
355
401
  server = create_server(simulation, port=0)
File without changes
File without changes
File without changes
File without changes