Skip to content

Commit

Permalink
feat: implement local storage
Browse files Browse the repository at this point in the history
  • Loading branch information
FabienArcellier committed Dec 9, 2024
1 parent 1efc789 commit 70cddab
Show file tree
Hide file tree
Showing 6 changed files with 48 additions and 7 deletions.
18 changes: 17 additions & 1 deletion src/ui/src/core/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {
AbstractTemplate,
Component,
ComponentMap,
InstancePath,
InstancePath, LocalStorageRemoveItemEvent, LocalStorageSetItemEvent,
MailItem,
UserFunction,
} from "@/writerTypes";
Expand Down Expand Up @@ -59,6 +59,12 @@ export function generateCore() {
addMailSubscription("pageChange", (pageKey: string) => {
setActivePageFromKey(pageKey);
});
addMailSubscription("localStorageSetItem", (event) => {
localStorage.setItem("wf." + event.key, JSON.stringify(event.value));
});
addMailSubscription("localStorageRemoveItem", (event) => {
localStorage.removeItem("wf." + event.key);
});
sendKeepAliveMessage();
if (mode.value != "edit") return;
}
Expand All @@ -69,6 +75,15 @@ export function generateCore() {
* @returns
*/
async function initSession() {
const localStorageItems = {};
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
if (key.startsWith("wf.")) {
const value = localStorage.getItem(key);
localStorageItems[key.replace("wf.", "")] = JSON.parse(value);
}
}

const response = await fetch("./api/init", {
method: "post",
cache: "no-store",
Expand All @@ -77,6 +92,7 @@ export function generateCore() {
},
body: JSON.stringify({
proposedSessionId: sessionId,
localStorage: localStorageItems,
}),
});
const initData = await response.json();
Expand Down
9 changes: 9 additions & 0 deletions src/ui/src/writerTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,3 +164,12 @@ export type AbstractTemplate = {
};

export type TemplateMap = Record<string, VueComponent>;

export type LocalStorageSetItemEvent = {
key: string;
value: string;
};

export type LocalStorageRemoveItemEvent = {
key: string;
};
2 changes: 1 addition & 1 deletion src/writer/app_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ def _handle_session_init(self, payload: InitSessionRequestPayload) -> InitSessio

session = writer.session_manager.get_session(payload.proposedSessionId, restore_initial_mail=True)
if session is None:
session = writer.session_manager.get_new_session(payload.cookies, payload.headers, payload.proposedSessionId)
session = writer.session_manager.get_new_session(payload.cookies, payload.headers, payload.localStorage, payload.proposedSessionId)

if session is None:
raise MessageHandlingException("Session rejected.")
Expand Down
19 changes: 16 additions & 3 deletions src/writer/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,10 +138,11 @@ class WriterSession:
Represents a session.
"""

def __init__(self, session_id: str, cookies: Optional[Dict[str, str]], headers: Optional[Dict[str, str]]) -> None:
def __init__(self, session_id: str, cookies: Optional[Dict[str, str]], headers: Optional[Dict[str, str]], local_storage: Optional[Dict[str, Any]]) -> None:
self.session_id = session_id
self.cookies = cookies
self.headers = headers
self.local_storage = local_storage
self.last_active_timestamp: int = int(time.time())
new_state = WriterState.get_new()
new_state.user_state.mutated = set()
Expand Down Expand Up @@ -1078,6 +1079,17 @@ def call_frontend_function(self, module_key: str, function_name: str, args: List
"args": args
})

def local_storage_set_item(self, key: str, value: Any) -> None:
self.add_mail("localStorageSetItem", {
"key": key,
"value": value
})

def local_storage_remove_item(self, key: str, value: Any) -> None:
self.add_mail("localStorageRemoveItem", {
"key": key
})

class MiddlewareExecutor():
"""
A MiddlewareExecutor executes middleware in a controlled context. It allows writer framework
Expand Down Expand Up @@ -1518,7 +1530,7 @@ def _check_proposed_session_id(self, proposed_session_id: Optional[str]) -> bool
return True
return False

def get_new_session(self, cookies: Optional[Dict] = None, headers: Optional[Dict] = None, proposed_session_id: Optional[str] = None) -> Optional[WriterSession]:
def get_new_session(self, cookies: Optional[Dict] = None, headers: Optional[Dict] = None, local_storage: Optional[Dict[str, Any]] = None, proposed_session_id: Optional[str] = None) -> Optional[WriterSession]:
if not self._check_proposed_session_id(proposed_session_id):
return None
if not self._verify_before_new_session(cookies, headers):
Expand All @@ -1528,7 +1540,7 @@ def get_new_session(self, cookies: Optional[Dict] = None, headers: Optional[Dict
new_id = self._generate_session_id()
else:
new_id = proposed_session_id
new_session = WriterSession(new_id, cookies, headers)
new_session = WriterSession(new_id, cookies, headers, local_storage)
self.sessions[new_id] = new_session
return new_session

Expand Down Expand Up @@ -2038,6 +2050,7 @@ def _event_handler_session_info() -> Dict[str, Any]:
session_info['cookies'] = current_session.cookies
session_info['headers'] = current_session.headers
session_info['userinfo'] = current_session.userinfo or {}
session_info['local_storage'] = current_session.local_storage or {}

return session_info

Expand Down
3 changes: 2 additions & 1 deletion src/writer/serve.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,8 @@ async def init(initBody: InitRequestBody, request: Request, response: Response)
app_response = await app_runner.init_session(InitSessionRequestPayload(
cookies=dict(request.cookies),
headers=dict(request.headers),
proposedSessionId=initBody.proposedSessionId
proposedSessionId=initBody.proposedSessionId,
localStorage=initBody.localStorage,
))

status = app_response.status
Expand Down
4 changes: 3 additions & 1 deletion src/writer/ss_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ class AbstractTemplate(BaseModel):

class InitRequestBody(BaseModel):
proposedSessionId: Optional[str] = None
localStorage: Optional[Dict[str, Any]] = None


class InitResponseBody(BaseModel):
Expand Down Expand Up @@ -83,6 +84,7 @@ class AppProcessServerRequest(BaseModel):
class InitSessionRequestPayload(BaseModel):
cookies: Optional[Dict[str, str]] = None
headers: Optional[Dict[str, str]] = None
localStorage: Optional[Dict[str, Any]] = None
proposedSessionId: Optional[str] = None

class InitSessionRequest(AppProcessServerRequest):
Expand Down Expand Up @@ -216,4 +218,4 @@ class WorkflowExecutionLog(BaseModel):


class WriterConfigurationError(ValueError):
pass
pass

0 comments on commit 70cddab

Please sign in to comment.