gnunet-svn
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[taler-wallet-core] branch master updated (c83d9465e -> 1facde4ab)


From: gnunet
Subject: [taler-wallet-core] branch master updated (c83d9465e -> 1facde4ab)
Date: Fri, 01 Mar 2024 15:50:59 +0100

This is an automated email from the git hooks/post-receive script.

sebasjm pushed a change to branch master
in repository wallet-core.

    from c83d9465e taler-harness: test for dev experiment
     new d09c50bdb move the wallet listener to background
     new 1facde4ab send a new request id to wallet instead of client request id

The 2 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 packages/taler-wallet-core/src/wallet.ts           |  5 +-
 .../src/components/WalletActivity.tsx              | 87 ++++++++++------------
 .../src/platform/chrome.ts                         |  3 +-
 .../src/wallet/Settings.tsx                        |  6 +-
 packages/taler-wallet-webextension/src/wxApi.ts    | 11 ++-
 .../taler-wallet-webextension/src/wxBackend.ts     | 45 ++++++++---
 6 files changed, 95 insertions(+), 62 deletions(-)

diff --git a/packages/taler-wallet-core/src/wallet.ts 
b/packages/taler-wallet-core/src/wallet.ts
index 879508036..28d54fde3 100644
--- a/packages/taler-wallet-core/src/wallet.ts
+++ b/packages/taler-wallet-core/src/wallet.ts
@@ -530,13 +530,14 @@ async function dumpCoins(wex: WalletExecutionContext): 
Promise<CoinDumpJson> {
 /**
  * Get an API client from an internal wallet state object.
  */
+let id = 0;
 async function getClientFromWalletState(
   ws: InternalWalletState,
 ): Promise<WalletCoreApiClient> {
-  let id = 0;
   const client: WalletCoreApiClient = {
     async call(op, payload): Promise<any> {
-      const res = await handleCoreApiRequest(ws, op, `${id++}`, payload);
+      id = (id + 1) % (Number.MAX_SAFE_INTEGER - 100);
+      const res = await handleCoreApiRequest(ws, op, String(id), payload);
       switch (res.type) {
         case "error":
           throw TalerError.fromUncheckedDetail(res.error);
diff --git 
a/packages/taler-wallet-webextension/src/components/WalletActivity.tsx 
b/packages/taler-wallet-webextension/src/components/WalletActivity.tsx
index 4a3aaf79f..1dde08010 100644
--- a/packages/taler-wallet-webextension/src/components/WalletActivity.tsx
+++ b/packages/taler-wallet-webextension/src/components/WalletActivity.tsx
@@ -35,6 +35,7 @@ import { useSettings } from "../hooks/useSettings.js";
 import { Button } from "../mui/Button.js";
 import { Modal } from "./Modal.js";
 import { Time } from "./Time.js";
+import { WalletEvent } from "../wxApi.js";
 
 interface Props extends JSX.HTMLAttributes {
 }
@@ -85,7 +86,7 @@ export function WalletActivity({ }: Props): VNode {
       {(function (): VNode {
         switch (table) {
           case "events": {
-            return <ObservavilityEventsTable />
+            return <ObservabilityEventsTable />
           }
           case "tasks": {
             return <ActiveTasksTable />
@@ -613,63 +614,56 @@ function getNotificationFor(id: string, event: 
WalletNotification, start: Absolu
   }
 }
 
-export function ObservavilityEventsTable({ }: {}): VNode {
+export function ObservabilityEventsTable({ }: {}): VNode {
   const { i18n } = useTranslationContext()
-  const listenAllEvents = Array.from<NotificationType>({ length: 1 });
-  listenAllEvents.includes = () => true
   const api = useBackendContext();
-  const [lastEvent, setLastEvent] = useState<Date>(new Date())
-  const [lastShow, setLastShow] = useState<Date>(new Date())
 
-  const [notifications, setNotifications] = useState<{ notif: 
WalletNotification, when: AbsoluteTime }[]>([])
+  const [notifications, setNotifications] = useState<Notif[]>([])
+  const [showDetails, setShowDetails] = useState<VNode>()
+
   useEffect(() => {
-    return api.listener.onUpdateNotification(listenAllEvents, (not) => {
-      console.log(not)
-      const time = new Date();
-      setLastEvent(time)
-      notifications.unshift({
-        notif: not,
-        when: AbsoluteTime.now()
+    let lastTimeout: ReturnType<typeof setTimeout>;
+    function periodicRefresh() {
+      api.background.call("getNotifications", undefined).then(notif => {
+
+        const list: Notif[] = []
+        for (const pepe of notif) {
+          const event = getNotificationFor(String(list.length), 
pepe.notification, pepe.when, list)
+          // pepe.
+          if (event) {
+            list.unshift(event)
+          }
+        }
+        setNotifications(list);
+      }).catch(error => {
+        console.log(error)
       })
-      setNotifications(Array.from(notifications))
-    });
-  });
 
-  const [showDetails, setShowDetails] = useState<VNode>()
-  const [notif, setnotif] = useState<Notif[]>([])
+      lastTimeout = setTimeout(() => {
+        periodicRefresh();
+      }, 1000)
+
+      //clear on unload 
+      return () => { clearTimeout(lastTimeout) }
+    }
+    return periodicRefresh()
+  }, [1]);
+
   return <div>
     <div style={{ display: "flex", justifyContent: "space-between" }}>
-      {lastShow === lastEvent ?
-        <div>last event {lastEvent.toString()}</div>
-        : <div>there are more events, update to see them</div>}
-      <div>
-        {lastShow !== lastEvent ?
-          <div style={{ padding: 4, margin: 2, border: "solid 1px black" }} 
onClick={() => {
-            const list = [...notif]
-            for (const pepe of notifications) {
-              const event = getNotificationFor(String(list.length), 
pepe.notif, pepe.when, list)
-              if (event) {
-                list.push(event)
-              }
-            }
-            setnotif(list)
-            setLastShow(lastEvent)
-          }}>
-            update
-          </div>
-          : <div />}
-        <div style={{ padding: 4, margin: 2, border: "solid 1px black" }} 
onClick={() => {
-          setNotifications([])
-        }}>
-          clear
-        </div>
 
+      <div style={{ padding: 4, margin: 2, border: "solid 1px black" }} 
onClick={() => {
+        setNotifications([])
+      }}>
+        clear
       </div>
+
+
     </div>
     {showDetails && <Modal title="event details" onClose={{ onClick: (async () 
=> { setShowDetails(undefined) }) as any }} >
       {showDetails}
     </Modal>}
-    {notif.map((not) => {
+    {notifications.map((not) => {
       return (
         <details key={not.id}>
           <summary>
@@ -721,14 +715,15 @@ function ErroDetailModal({ error, onClose }: { error: 
TalerErrorDetail, onClose:
 
 export function ActiveTasksTable({ }: {}): VNode {
   const { i18n } = useTranslationContext()
-  const listenAllEvents = Array.from<NotificationType>({ length: 1 });
-  listenAllEvents.includes = () => true
   const api = useBackendContext();
   const state = useAsyncAsHook(() =>
     api.wallet.call(WalletApiOperation.GetActiveTasks, {}),
   );
   const [showError, setShowError] = useState<TalerErrorDetail>()
   const tasks = state && !state.hasError ? state.response.tasks : [];
+
+  // const listenAllEvents = Array.from<NotificationType>({ length: 1 });
+  // listenAllEvents.includes = () => true
   // useEffect(() => {
   //   return api.listener.onUpdateNotification(listenAllEvents, (notif) => {
   //     state?.retry()
diff --git a/packages/taler-wallet-webextension/src/platform/chrome.ts 
b/packages/taler-wallet-webextension/src/platform/chrome.ts
index fc2d1db09..68b065853 100644
--- a/packages/taler-wallet-webextension/src/platform/chrome.ts
+++ b/packages/taler-wallet-webextension/src/platform/chrome.ts
@@ -281,7 +281,8 @@ let nextMessageIndex = 0;
 async function sendMessageToBackground<
   Op extends WalletOperations | BackgroundOperations,
 >(message: MessageFromFrontend<Op>): Promise<MessageResponse> {
-  const messageWithId = { ...message, id: `id_${nextMessageIndex++ % 1000}` };
+  nextMessageIndex = (nextMessageIndex + 1) % (Number.MAX_SAFE_INTEGER - 100);
+  const messageWithId = { ...message, id: `id_${nextMessageIndex}` };
 
   return new Promise<any>((resolve, reject) => {
     logger.trace("send operation to the wallet background", message);
diff --git a/packages/taler-wallet-webextension/src/wallet/Settings.tsx 
b/packages/taler-wallet-webextension/src/wallet/Settings.tsx
index 64a96d643..e35e6d241 100644
--- a/packages/taler-wallet-webextension/src/wallet/Settings.tsx
+++ b/packages/taler-wallet-webextension/src/wallet/Settings.tsx
@@ -25,7 +25,7 @@ import {
   WalletCoreVersion,
 } from "@gnu-taler/taler-util";
 import { WalletApiOperation } from "@gnu-taler/taler-wallet-core";
-import { useTranslationContext } from "@gnu-taler/web-util/browser";
+import { useApiContext, useTranslationContext } from 
"@gnu-taler/web-util/browser";
 import { Fragment, VNode, h } from "preact";
 import { Pages } from "../NavigationBar.js";
 import { Checkbox } from "../components/Checkbox.js";
@@ -231,6 +231,7 @@ type Options = {
 };
 function AdvanceSettings(): VNode {
   const [settings, updateSettings] = useSettings();
+  const api = useBackendContext();
   const { i18n } = useTranslationContext();
   const o: Options = {
     backup: {
@@ -271,7 +272,7 @@ function AdvanceSettings(): VNode {
     },
     showWalletActivity: {
       label: i18n.str`Show wallet activity`,
-      description: i18n.str`Show the wallet notification and observavility 
event in the UI.`,
+      description: i18n.str`Show the wallet notification and observability 
event in the UI.`,
     },
   };
   return (
@@ -287,6 +288,7 @@ function AdvanceSettings(): VNode {
               enabled={settings[settingsName]}
               onToggle={async () => {
                 updateSettings(settingsName, !settings[settingsName]);
+                await api.background.call("reinitWallet", undefined);
               }}
             />
           );
diff --git a/packages/taler-wallet-webextension/src/wxApi.ts 
b/packages/taler-wallet-webextension/src/wxApi.ts
index a1c09ef8d..c53b15ef0 100644
--- a/packages/taler-wallet-webextension/src/wxApi.ts
+++ b/packages/taler-wallet-webextension/src/wxApi.ts
@@ -70,6 +70,14 @@ export interface BackgroundOperations {
     request: void;
     response: void;
   };
+  reinitWallet: {
+    request: void;
+    response: void;
+  };
+  getNotifications: {
+    request: void;
+    response: WalletEvent[];
+  };
   setLoggingLevel: {
     request: {
       tag?: string;
@@ -79,6 +87,8 @@ export interface BackgroundOperations {
   };
 }
 
+export type WalletEvent = { notification: WalletNotification, when: 
AbsoluteTime }
+
 export interface BackgroundApiClient {
   call<Op extends keyof BackgroundOperations>(
     operation: Op,
@@ -182,7 +192,6 @@ function onUpdateNotification(
   const onNewMessage = (message: MessageFromBackend): void => {
     const shouldNotify = message.type === "wallet" && 
messageTypes.includes(message.notification.type);
     if (shouldNotify) {
-      message.notification
       doCallback(message.notification);
     }
   };
diff --git a/packages/taler-wallet-webextension/src/wxBackend.ts 
b/packages/taler-wallet-webextension/src/wxBackend.ts
index 0801d2ab0..7c090b28b 100644
--- a/packages/taler-wallet-webextension/src/wxBackend.ts
+++ b/packages/taler-wallet-webextension/src/wxBackend.ts
@@ -24,6 +24,7 @@
  * Imports.
  */
 import {
+  AbsoluteTime,
   LogLevel,
   Logger,
   OpenedPromise,
@@ -33,7 +34,7 @@ import {
   makeErrorDetail,
   openPromise,
   setGlobalLogLevelFromString,
-  setLogLevelFromString,
+  setLogLevelFromString
 } from "@gnu-taler/taler-util";
 import { HttpRequestLibrary } from "@gnu-taler/taler-util/http";
 import {
@@ -53,7 +54,7 @@ import {
 import { MessageFromFrontend, MessageResponse } from "./platform/api.js";
 import { platform } from "./platform/background.js";
 import { ExtensionOperations } from "./taler-wallet-interaction-loader.js";
-import { BackgroundOperations } from "./wxApi.js";
+import { BackgroundOperations, WalletEvent } from "./wxApi.js";
 
 /**
  * Currently active wallet instance.  Might be unloaded and
@@ -91,6 +92,12 @@ async function resetDb(): Promise<void> {
   await reinitWallet();
 }
 
+//FIXME: maybe circular buffer
+const notifications: WalletEvent[] = []
+async function getNotifications(): Promise<WalletEvent[]> {
+  return notifications
+}
+
 async function runGarbageCollector(): Promise<void> {
   const dbBeforeGc = currentDatabase;
   if (!dbBeforeGc) {
@@ -129,6 +136,8 @@ async function isDomainTrusted(): Promise<boolean> {
 const backendHandlers: BackendHandlerType = {
   resetDb,
   runGarbageCollector,
+  getNotifications,
+  reinitWallet,
   setLoggingLevel,
 };
 
@@ -146,10 +155,13 @@ async function setLoggingLevel({
     setLogLevelFromString(tag, level);
   }
 }
+let nextMessageIndex = 0;
 
 async function dispatch<
   Op extends WalletOperations | BackgroundOperations | ExtensionOperations,
 >(req: MessageFromFrontend<Op> & { id: string }): Promise<MessageResponse> {
+  nextMessageIndex = (nextMessageIndex + 1) % (Number.MAX_SAFE_INTEGER - 100);
+
   switch (req.channel) {
     case "background": {
       const handler = backendHandlers[req.operation] as (req: any) => any;
@@ -223,8 +235,12 @@ async function dispatch<
           ),
         };
       }
-
-      return await w.handleCoreApiRequest(req.operation, req.id, req.payload);
+      //multiple client can create the same id, send the wallet an unique key
+      const newId = `${req.id}_${nextMessageIndex}`
+      const resp = await w.handleCoreApiRequest(req.operation, newId, 
req.payload);
+      //return to the client the original id
+      resp.id = req.id
+      return resp
     }
   }
 
@@ -284,12 +300,14 @@ async function reinitWallet(): Promise<void> {
   );
   try {
     await wallet.handleCoreApiRequest("initWallet", "native-init", {
-      testing: {
-        emitObservabilityEvents: true,
-      },
-      features: {
-        allowHttp: settings.walletAllowHttp,
-      },
+      config: {
+        testing: {
+          emitObservabilityEvents: settings.showWalletActivity,
+        },
+        features: {
+          allowHttp: settings.walletAllowHttp,
+        },
+      }
     });
   } catch (e) {
     logger.error("could not initialize wallet", e);
@@ -297,6 +315,13 @@ async function reinitWallet(): Promise<void> {
     return;
   }
   wallet.addNotificationListener((message) => {
+    if (settings.showWalletActivity) {
+      notifications.push({
+        notification: message,
+        when: AbsoluteTime.now()
+      })
+    }
+
     platform.sendMessageToAllChannels({
       type: "wallet",
       notification: message,

-- 
To stop receiving notification emails like this one, please contact
gnunet@gnunet.org.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]