Skip to content
This repository has been archived by the owner on Feb 15, 2024. It is now read-only.

Commit

Permalink
Initialize client id if need before anything else (#976) (#983)
Browse files Browse the repository at this point in the history
* Initialize client id if need before anything else

* init_route was happening before the first request for id

* prevent access before an id is defined

* lint

---------

Co-authored-by: Fred Lefévère-Laoide <[email protected]>
Co-authored-by: dinhlongnguyen <[email protected]>
  • Loading branch information
3 people authored Oct 19, 2023
1 parent 38a23b4 commit 0598948
Show file tree
Hide file tree
Showing 7 changed files with 50 additions and 47 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ jobs:
raise ValueError(f\"Invalid version {version} / {sys.argv[1]}\")
if sys.argv[1] != sys.argv[2]:
raise ValueError(f\"Invalid tag version {sys.argv[2]} with package version {sys.argv[1]}\")
""" > /tmp/check.py
python /tmp/check.py "${{ github.event.inputs.version }}" "${{ steps.vars.outputs.tag }}"
""" > ${{ runner.temp }}/check.py
python ${{ runner.temp }}p/check.py "${{ github.event.inputs.version }}" "${{ steps.vars.outputs.tag }}"
- name: Download assets from github release tag
run: |
Expand Down
31 changes: 8 additions & 23 deletions .github/workflows/release-dev.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,21 +21,6 @@ jobs:
with:
node-version: '18'

# - name: Extract branch name
# shell: bash
# run: echo "BRANCH=${GITHUB_REF#refs/heads/}" >> $GITHUB_OUTPUT
# id: extract_branch

# - name: Validate branch name (has 'dev' prefix)
# run: |
# echo """
# import sys
# PREFIX = 'dev'
# if not sys.argv[1].startswith(PREFIX):
# raise ValueError(f'Branch name must start with \"{PREFIX}\"')
# """ > /tmp/check.py
# python /tmp/check.py "${{ steps.extract_branch.outputs.BRANCH }}"

- name: Ensure package version has 'dev' suffix
run: |
echo """
Expand All @@ -48,8 +33,8 @@ jobs:
version = f'{version}.{vext}'
if SUFFIX not in version:
raise ValueError(f\"version {version} does not contain suffix {SUFFIX}\")
""" > /tmp/check1.py
python /tmp/check1.py
""" > ${{ runner.temp }}/check1.py
python ${{ runner.temp }}/check1.py
- name: Extract package version
id: current-version
Expand All @@ -62,8 +47,8 @@ jobs:
if vext := version_o.get(\"ext\"):
version = f'{version}.{vext}'
print(f'VERSION={version}')
""" > /tmp/check2.py
python /tmp/check2.py >> $GITHUB_OUTPUT
""" > ${{ runner.temp }}/check2.py
python ${{ runner.temp }}/check2.py >> $GITHUB_OUTPUT
- name: Install dependencies
run: |
Expand Down Expand Up @@ -97,8 +82,8 @@ jobs:
end = line.rstrip().find(',')
line = f'{line[:start]}\"taipy-config=={sys.argv[1]}\"{line[end:]}'
setup_w.write(line)
""" > /tmp/write_setup_taipy.py
python /tmp/write_setup_taipy.py "${{ github.event.inputs.taipy-config-version }}"
""" > ${{ runner.temp }}/write_setup_taipy.py
python ${{ runner.temp }}/write_setup_taipy.py "${{ github.event.inputs.taipy-config-version }}"
- name: Generate pyi files
run: |
Expand Down Expand Up @@ -169,8 +154,8 @@ jobs:
if vext := version_o.get(\"ext\"):
version = f'{version}.{vext}'
print(f'VERSION={version}')
""" > /tmp/increase_dev_version.py
python /tmp/increase_dev_version.py >> $GITHUB_OUTPUT
""" > ${{ runner.temp }}/increase_dev_version.py
python ${{ runner.temp }}/increase_dev_version.py >> $GITHUB_OUTPUT
- uses: stefanzweifel/git-auto-commit-action@v4
with:
Expand Down
8 changes: 4 additions & 4 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ jobs:
version = f'{version}.{vext}'
if version != sys.argv[1]:
raise ValueError(f\"Invalid version {version} / {sys.argv[1]}\")
""" > /tmp/check1.py
python /tmp/check1.py "${{ github.event.inputs.version }}"
""" > ${{ runner.temp }}/check1.py
python ${{ runner.temp }}/check1.py "${{ github.event.inputs.version }}"
- name: Validate branch name
run: |
Expand All @@ -50,8 +50,8 @@ jobs:
version = json.load(version_file)
if f'release/{version.get(\"major\")}.{version.get(\"minor\")}' != sys.argv[1]:
raise ValueError(f'Branch name mismatch: release/{version.get(\"major\")}.{version.get(\"minor\")} != {sys.argv[1]}')
""" > /tmp/check.py
python /tmp/check.py "${{ steps.extract_branch.outputs.BRANCH }}"
""" > ${{ runner.temp }}/check.py
python ${{ runner.temp }}/check.py "${{ steps.extract_branch.outputs.BRANCH }}"
- name: Install dependencies
run: |
Expand Down
25 changes: 17 additions & 8 deletions gui/src/context/taipyReducers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,8 @@ export const getLocalStorageValue = <T = string>(key: string, defaultValue: T, v
return !val ? defaultValue : !values ? val : values.indexOf(val) == -1 ? defaultValue : val;
};

const TAIPY_CLIENT_ID = "TaipyClientId";

export const INITIAL_STATE: TaipyState = {
data: {},
theme: window.taipyConfig?.darkMode ? themes.dark : themes.light,
Expand All @@ -199,7 +201,7 @@ export const INITIAL_STATE: TaipyState = {
? TIMEZONE_CLIENT
: window.taipyConfig.timeZone
: undefined,
id: getLocalStorageValue("TaipyClientId", ""),
id: getLocalStorageValue(TAIPY_CLIENT_ID, ""),
menu: {},
ackList: [],
alerts: [],
Expand All @@ -211,7 +213,7 @@ export const taipyInitialize = (initialState: TaipyState): TaipyState => ({
socket: io("/", { autoConnect: false, path: `${getBaseURL()}socket.io` }),
});

const storeClientId = (id: string) => localStorage && localStorage.setItem("TaipyClientId", id);
const storeClientId = (id: string) => localStorage && localStorage.setItem(TAIPY_CLIENT_ID, id);

const messageToAction = (message: WsMessage) => {
if (message.type) {
Expand Down Expand Up @@ -267,9 +269,10 @@ export const initializeWebSocket = (socket: Socket | undefined, dispatch: Dispat
if (socket) {
// Websocket confirm successful initialization
socket.on("connect", () => {
const id = getLocalStorageValue("TaipyClientId", "");
sendWsMessage(socket, "ID", "TaipyClientId", id, id);
dispatch({ type: Types.SocketConnected });
const id = getLocalStorageValue(TAIPY_CLIENT_ID, "");
sendWsMessage(socket, "ID", TAIPY_CLIENT_ID, id, id, undefined, false, () => {
dispatch({ type: Types.SocketConnected });
});
});
// try to reconnect on connect_error
socket.on("connect_error", () => {
Expand Down Expand Up @@ -778,7 +781,12 @@ export const createBlockAction = (block: BlockMessage): TaipyBlockAction => ({
message: block.message,
});

export const createNavigateAction = (to?: string, params?: Record<string, string>, tab?: string, force?: boolean): TaipyNavigateAction => ({
export const createNavigateAction = (
to?: string,
params?: Record<string, string>,
tab?: string,
force?: boolean
): TaipyNavigateAction => ({
type: Types.Navigate,
to,
params,
Expand Down Expand Up @@ -833,7 +841,8 @@ const sendWsMessage = (
payload: Record<string, unknown> | unknown,
id: string,
moduleContext = "",
propagate = true
propagate = true,
serverAck?: (val: unknown) => void
): string => {
const ackId = uuidv4();
const msg: WsMessage = {
Expand All @@ -845,6 +854,6 @@ const sendWsMessage = (
ack_id: ackId,
module_context: moduleContext,
};
socket?.emit("message", msg);
socket?.emit("message", msg, serverAck);
return ackId;
};
22 changes: 14 additions & 8 deletions src/taipy/gui/gui.py
Original file line number Diff line number Diff line change
Expand Up @@ -460,9 +460,12 @@ def _get_client_id(self) -> str:
else getattr(g, Gui.__ARG_CLIENT_ID, "unknown id")
)

def __set_client_id_in_context(self, client_id: t.Optional[str] = None):
def __set_client_id_in_context(self, client_id: t.Optional[str] = None, force=False):
if not client_id and request:
client_id = request.args.get(Gui.__ARG_CLIENT_ID, "")
if not client_id and force:
res = self._bindings()._get_or_create_scope("")
client_id = res[0] if res[1] else None
if client_id and request:
if sid := getattr(request, "sid", None):
sids = self.__client_id_2_sid.get(client_id, None)
Expand Down Expand Up @@ -502,7 +505,11 @@ def __clean_vars_on_exit(self) -> t.Optional[t.Set[str]]:

def _manage_message(self, msg_type: _WsType, message: dict) -> None:
try:
self.__set_client_id_in_context(message.get(Gui.__ARG_CLIENT_ID))
client_id = None
if msg_type == _WsType.CLIENT_ID.value:
res = self._bindings()._get_or_create_scope(message.get("payload", ""))
client_id = res[0] if res[1] else None
self.__set_client_id_in_context(client_id or message.get(Gui.__ARG_CLIENT_ID))
self._set_locals_context(message.get("module_context") or None)
if msg_type == _WsType.UPDATE.value:
payload = message.get("payload", {})
Expand All @@ -519,8 +526,6 @@ def _manage_message(self, msg_type: _WsType, message: dict) -> None:
self.__request_data_update(str(message.get("name")), message.get("payload"))
elif msg_type == _WsType.REQUEST_UPDATE.value:
self.__request_var_update(message.get("payload"))
elif msg_type == _WsType.CLIENT_ID.value:
self._bindings()._get_or_create_scope(message.get("payload", ""))
self._reset_locals_context()
self.__send_ack(message.get("ack_id"))
except Exception as e: # pragma: no cover
Expand Down Expand Up @@ -916,8 +921,8 @@ def __request_var_update(self, payload: t.Any):
)
self.__send_var_list_update(payload["names"])

def __send_ws(self, payload: dict) -> None:
grouping_message = self.__get_message_grouping()
def __send_ws(self, payload: dict, allow_grouping=True) -> None:
grouping_message = self.__get_message_grouping() if allow_grouping else None
if grouping_message is None:
try:
self._server._ws.emit(
Expand Down Expand Up @@ -954,7 +959,8 @@ def _send_ws_id(self, id: str) -> None:
{
"type": _WsType.CLIENT_ID.value,
"id": id,
}
},
allow_grouping=False,
)

def __send_ws_download(self, content: str, name: str, on_action: str) -> None:
Expand Down Expand Up @@ -1719,7 +1725,7 @@ def __init_libs(self):
_warn(f"Exception raised in {name}.on_user_init()", e)

def __init_route(self):
self.__set_client_id_in_context()
self.__set_client_id_in_context(force=True)
if not _hasscopeattr(self, Gui.__ON_INIT_NAME):
_setscopeattr(self, Gui.__ON_INIT_NAME, True)
self.__pre_render_pages()
Expand Down
3 changes: 2 additions & 1 deletion src/taipy/gui/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,8 +102,9 @@ def __init__(
self._is_running = False

# Websocket (handle json message)
# adding args for the one call with a server ack request
@self._ws.on("message")
def handle_message(message) -> None:
def handle_message(message, *args) -> None:
if "status" in message:
_TaipyLogger._get_logger().info(message["status"])
elif "type" in message:
Expand Down
4 changes: 3 additions & 1 deletion src/taipy/gui/utils/_bindings.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,10 +59,12 @@ def _is_single_client(self) -> bool:
return self.__scopes.is_single_client()

def _get_or_create_scope(self, id: str):
if not id:
create = not id
if create:
id = f"{datetime.now().strftime('%Y%m%d%H%M%S%f')}-{random()}"
self.__gui._send_ws_id(id)
self.__scopes.create_scope(id)
return id, create

def _new_scopes(self):
self.__scopes = _DataScopes()
Expand Down

0 comments on commit 0598948

Please sign in to comment.