Skip to content
This repository was archived by the owner on Jan 15, 2025. It is now read-only.

Commit 9f88a1b

Browse files
getneilneil molina
andauthored
move auth polling strategy to main thread (#546)
* #545 move auth polling strategy to main thread * #545 remove unused * bum v0.1.1 --------- Co-authored-by: neil molina <neil@neils-MacBook-Pro.local>
1 parent 1a0289f commit 9f88a1b

8 files changed

Lines changed: 84 additions & 66 deletions

File tree

modules/desktop/electron/electron.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -196,7 +196,7 @@ app.on("open-url", (event, url) => {
196196
}
197197
});
198198

199-
function notifyMainWindow(channel: string, data: unknown) {
199+
export function notifyMainWindow(channel: string, data: unknown) {
200200
if (mainWindow && !mainWindow.isDestroyed()) {
201201
mainWindow.webContents.send(channel, data);
202202
}

modules/desktop/electron/libs/auth.ts

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,9 @@ import { getTeaPath } from "./tea-dir";
55
import { app } from "electron";
66
import log from "./logger";
77
import axios from "axios";
8+
import get from "./v1-client";
9+
import { DeviceAuth } from "../../src/libs/types";
10+
import { notifyMainWindow } from "../electron";
811

912
const sessionFilePath = path.join(getTeaPath(), "tea.xyz/gui/tmp.dat");
1013
const sessionFolder = path.join(getTeaPath(), "tea.xyz/gui");
@@ -152,3 +155,44 @@ export async function writeSessionData(data: Session, force?: boolean) {
152155
log.error(error);
153156
}
154157
}
158+
159+
let pollInterval: NodeJS.Timer | null;
160+
let pollLoop = 0;
161+
export async function pollAuth() {
162+
if (!pollInterval) {
163+
log.info("polling auth starts...");
164+
const session = await readSessionData();
165+
pollInterval = setInterval(async () => {
166+
pollLoop++;
167+
log.info("poll auth retry:", pollLoop);
168+
let clear = false;
169+
let success = false;
170+
try {
171+
const data = await get<DeviceAuth>(`/auth/device/${session.device_id}`);
172+
if (data?.status === "SUCCESS") {
173+
await writeSessionData({
174+
key: data.key,
175+
user: data.user
176+
});
177+
clear = true;
178+
success = true;
179+
} else if (pollLoop > 20 && pollInterval) {
180+
clear = true;
181+
}
182+
} catch (error) {
183+
log.error(error);
184+
clear = true;
185+
} finally {
186+
if (clear) {
187+
pollInterval && clearInterval(pollInterval);
188+
pollInterval = null;
189+
log.info("polling auth ends.");
190+
}
191+
if (success) {
192+
log.info("updating renderer session");
193+
notifyMainWindow("session-update", sessionMemory);
194+
}
195+
}
196+
}, 2000);
197+
}
198+
}

modules/desktop/electron/libs/ipc.ts

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { ipcMain, app, BrowserWindow } from "electron";
22
import { deletePackageFolder, getInstalledPackages, cacheImage } from "./tea-dir";
3-
import { readSessionData, writeSessionData } from "./auth";
3+
import { readSessionData, writeSessionData, pollAuth } from "./auth";
44
import type { Packages, Session } from "../../src/libs/types";
55
import log from "./logger";
66
import { syncLogsAt } from "./v1-client";
@@ -205,4 +205,13 @@ export default function initializeHandlers({ notifyMainWindow }: HandlerOptions)
205205
log.error(error);
206206
}
207207
});
208+
209+
ipcMain.handle("poll-session", async () => {
210+
try {
211+
log.info("start polling");
212+
return pollAuth();
213+
} catch (error) {
214+
log.error(error);
215+
}
216+
});
208217
}

modules/desktop/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "tea",
3-
"version": "0.1.0",
3+
"version": "0.1.1",
44
"private": true,
55
"description": "tea gui app",
66
"author": "tea.xyz",

modules/desktop/src/components/top-bar/login-button.svelte

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
<script lang="ts">
2-
import { authStore, navStore } from "$libs/stores";
2+
import { authStore } from "$libs/stores";
33
import { getSession } from "@native";
44
import { baseUrl } from "$libs/v1-client";
5-
import { shellOpenExternal } from "@native";
5+
import { shellOpenExternal, pollDeviceSession } from "@native";
66
import mouseLeaveDelay from "@tea/ui/lib/mouse-leave-delay";
77
const { user } = authStore;
88
@@ -18,7 +18,7 @@
1818
1919
if (session && session.device_id) {
2020
shellOpenExternal(`${baseUrl}/auth/user?device_id=${session.device_id}`);
21-
authStore.pollSession();
21+
pollDeviceSession();
2222
} else {
2323
throw new Error("possible no internet connection");
2424
}

modules/desktop/src/libs/native-electron.ts

Lines changed: 9 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -12,14 +12,7 @@
1212
*/
1313

1414
import type { Package, Review, AirtablePost, Bottle } from "@tea/ui/types";
15-
import {
16-
type GUIPackage,
17-
type DeviceAuth,
18-
type Session,
19-
AuthStatus,
20-
type Packages,
21-
type AutoUpdateStatus
22-
} from "./types";
15+
import type { GUIPackage, Session, Packages, AutoUpdateStatus } from "./types";
2316

2417
import * as mock from "./native-mock";
2518
import { PackageStates, type InstalledPackage } from "./types";
@@ -130,21 +123,6 @@ export async function getAllPosts(tag?: string): Promise<AirtablePost[]> {
130123
}
131124
}
132125

133-
export async function getDeviceAuth(deviceId: string): Promise<DeviceAuth> {
134-
let auth: DeviceAuth = {
135-
status: AuthStatus.UNKNOWN,
136-
key: ""
137-
};
138-
try {
139-
const data = await apiGet<DeviceAuth>(`/auth/device/${deviceId}`);
140-
if (data) auth = data;
141-
} catch (error) {
142-
log.error(error);
143-
auth = await getDeviceAuth(deviceId);
144-
}
145-
return auth;
146-
}
147-
148126
export async function getPackageBottles(packageName: string): Promise<Bottle[]> {
149127
try {
150128
return withRetry(async () => {
@@ -296,3 +274,11 @@ export const getAutoUpdateStatus = async (): Promise<AutoUpdateStatus> => {
296274
return { status: "up-to-date" };
297275
}
298276
};
277+
278+
export const pollDeviceSession = async () => {
279+
try {
280+
await ipcRenderer.invoke("poll-session");
281+
} catch (error) {
282+
log.error(error);
283+
}
284+
};

modules/desktop/src/libs/native-mock.ts

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -326,11 +326,6 @@ export async function getAllPosts(type: string): Promise<AirtablePost[]> {
326326
return posts;
327327
}
328328

329-
export async function getDeviceAuth(deviceId: string): Promise<any> {
330-
const data = await v1Client.get<any>(`/auth/device/${deviceId}`);
331-
return data;
332-
}
333-
334329
export async function getPackageBottles(name: string): Promise<Bottle[]> {
335330
return [
336331
{ name, platform: "darwin", arch: "aarch64", version: "3.39.4", bytes: 123456 },
@@ -411,3 +406,7 @@ export const getAutoUpdateStatus = async (): Promise<AutoUpdateStatus> => {
411406
export async function openPackageEntrypointInTerminal(pkg: string) {
412407
//noop
413408
}
409+
410+
export const pollDeviceSession = async () => {
411+
console.log("do nothing");
412+
};

modules/desktop/src/libs/stores/auth.ts

Lines changed: 12 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
import { writable } from "svelte/store";
22

3-
import { getDeviceAuth } from "@native";
3+
import { listenToChannel } from "@native";
44
import type { Developer } from "@tea/ui/types";
55
import type { Session } from "$libs/types";
66
import { getSession as electronGetSession, updateSession as electronUpdateSession } from "@native";
77
import { initSentry } from "../sentry";
8+
import log from "$libs/logger";
89

910
export let session: Session | null = null;
1011
export const getSession = async (): Promise<Session | null> => {
@@ -15,7 +16,6 @@ export const getSession = async (): Promise<Session | null> => {
1516
export default function initAuthStore() {
1617
const user = writable<Developer | undefined>();
1718
const sessionStore = writable<Session>({});
18-
let pollLoop = 0;
1919

2020
const deviceIdStore = writable<string>("");
2121
let deviceId = "";
@@ -31,7 +31,16 @@ export default function initAuthStore() {
3131
}
3232
});
3333

34-
let timer: NodeJS.Timer | null;
34+
listenToChannel("session-update", (data: Session) => {
35+
log.info("session update renderer", data);
36+
sessionStore.update((val) => ({
37+
...val,
38+
...data
39+
}));
40+
if (data.user) {
41+
user.set(data.user);
42+
}
43+
});
3544

3645
async function updateSession(data: Session) {
3746
sessionStore.update((val) => ({
@@ -43,34 +52,6 @@ export default function initAuthStore() {
4352
await electronUpdateSession(data);
4453
}
4554

46-
async function pollSession() {
47-
if (!timer) {
48-
timer = setInterval(async () => {
49-
pollLoop++;
50-
try {
51-
const data = await getDeviceAuth(deviceId);
52-
if (data.status === "SUCCESS") {
53-
updateSession({
54-
key: data.key,
55-
user: data.user
56-
});
57-
user.set(data.user!);
58-
timer && clearInterval(timer);
59-
timer = null;
60-
}
61-
} catch (error) {
62-
console.error(error);
63-
}
64-
65-
if (pollLoop > 20 && timer) {
66-
clearInterval(timer);
67-
pollLoop = 0;
68-
timer = null;
69-
}
70-
}, 2000);
71-
}
72-
}
73-
7455
function clearSession() {
7556
updateSession({ key: undefined, user: undefined });
7657
user.set(undefined);
@@ -81,7 +62,6 @@ export default function initAuthStore() {
8162
session: sessionStore,
8263
deviceId,
8364
deviceIdStore,
84-
pollSession,
8565
clearSession,
8666
updateSession
8767
};

0 commit comments

Comments
 (0)