浏览代码

stick socket.io connections to fly instances

Rodja Trappe 2 年之前
父节点
当前提交
ebc99c6613
共有 3 个文件被更改,包括 9 次插入1 次删除
  1. 1 0
      fly.toml
  2. 4 0
      nicegui/client.py
  3. 4 1
      nicegui/templates/index.html

+ 1 - 0
fly.toml

@@ -1,4 +1,5 @@
 app = "nicegui"
+#app = "nicegui-preview"
 kill_signal = "SIGTERM"
 kill_timeout = 5
 processes = []

+ 4 - 0
nicegui/client.py

@@ -1,5 +1,6 @@
 import asyncio
 import json
+import os
 import time
 import uuid
 from pathlib import Path
@@ -62,12 +63,15 @@ class Client:
         self.content.__exit__()
 
     def build_response(self, request: Request, status_code: int = 200) -> HTMLResponse:
+        fly_instance_id = os.environ.get('FLY_ALLOC_ID', '').split('-')[0]
+        print('fly instance id', fly_instance_id)
         prefix = request.headers.get('X-Forwarded-Prefix', '')
         vue_html, vue_styles, vue_scripts = vue.generate_vue_content()
         elements = json.dumps({id: element.to_dict() for id, element in self.elements.items()})
         return templates.TemplateResponse('index.html', {
             'request': request,
             'client_id': str(self.id),
+            'fly_instance_id': fly_instance_id,
             'elements': elements,
             'head_html': self.head_html,
             'body_html': f'{self.body_html}\n{vue_html}\n{vue_styles}',

+ 4 - 1
nicegui/templates/index.html

@@ -89,7 +89,10 @@
         mounted() {
           const query = { client_id: "{{ client_id }}" };
           const url = window.location.protocol === 'https:' ? 'wss://' : 'ws://' + window.location.host;
-          window.socket = io(url, { path: "{{ prefix | safe }}/ws/socket.io", query });
+          const extraHeaders = {
+            "fly-force-instance-id": "{{ fly_instance_id }}"
+          }
+          window.socket = io(url, { path: "{{ prefix | safe }}/ws/socket.io", query, extraHeaders });
           window.socket.on("connect", () => {
             window.socket.emit("handshake", (ok) => {
               if (!ok) window.location.reload();