-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathModelContext.tsx
More file actions
195 lines (172 loc) · 5.54 KB
/
ModelContext.tsx
File metadata and controls
195 lines (172 loc) · 5.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
import { AuthContext } from '@luna/contexts/api/auth/AuthContext';
import { LaserMetrics, UserModel } from '@luna/contexts/api/model/types';
import { useAsyncIterable } from '@luna/hooks/useAsyncIterable';
import { mergeAsyncIterables } from '@luna/utils/async';
import { errorResult, getOrThrow, okResult, Result } from '@luna/utils/result';
import { Map, Set } from 'immutable';
import {
connect,
ConsoleLogHandler,
DirectoryTree,
LeveledLogHandler,
Lighthouse,
LIGHTHOUSE_FRAME_BYTES,
LogLevel,
ServerMessage,
} from 'nighthouse/browser';
import {
createContext,
ReactNode,
useCallback,
useContext,
useEffect,
useMemo,
useState,
} from 'react';
export interface Users {
/** The user models by username. */
readonly models: Map<string, UserModel>;
/** The usernames of active users. */
readonly active: Set<string>;
}
export interface ModelContextValue {
/** The user models, active users etc. */
readonly users: Users;
/** Lists an arbitrary path. */
list(path: string[]): Promise<Result<DirectoryTree>>;
/** Fetches an arbitrary path. */
get(path: string[]): Promise<Result<unknown>>;
/** Fetches lamp server metrics. */
getLaserMetrics(): Promise<Result<LaserMetrics>>;
}
export const ModelContext = createContext<ModelContextValue>({
users: {
models: Map(),
active: Set(),
},
list: async () => errorResult('No model context for listing path'),
get: async () => errorResult('No model context for fetching path'),
getLaserMetrics: async () =>
errorResult('No model context for fetching laser metrics'),
});
interface ModelContextProviderProps {
children: ReactNode;
}
function messageToResult<T>(message: ServerMessage<T> | undefined): Result<T> {
try {
if (!message) {
return errorResult('Model server provided no results');
}
if (message.RNUM >= 400) {
return errorResult(
`Model server errored: ${message.RNUM} ${message.RESPONSE ?? ''}`
);
}
return okResult(message.PAYL);
} catch (error) {
return errorResult(error);
}
}
export function ModelContextProvider({ children }: ModelContextProviderProps) {
const auth = useContext(AuthContext);
const [isLoggedIn, setLoggedIn] = useState(false);
const [users, setUsers] = useState<Users>({
models: Map(),
active: Set(),
});
const [client, setClient] = useState<Lighthouse>();
const username = useMemo(() => auth.user?.username, [auth.user]);
const tokenValue = useMemo(() => auth.token?.value, [auth.token]);
// TODO: Expose more general CRUD methods of the nighthouse API
useEffect(() => {
let client: Lighthouse | undefined = undefined;
(async () => {
if (!username || !tokenValue) {
setLoggedIn(false);
return;
}
console.log(`Connecting as ${username}`);
client = connect({
url:
process.env.REACT_APP_MODEL_SERVER_URL ??
'wss://lighthouse.uni-kiel.de/websocket',
auth: { USER: username, TOKEN: tokenValue },
logHandler: new LeveledLogHandler(
LogLevel.Debug,
new ConsoleLogHandler('Nighthouse: ')
),
});
await client.ready();
setClient(client);
setLoggedIn(true);
})();
return () => {
(async () => {
await client?.close();
})();
};
}, [username, tokenValue]);
const getUserStreams = useCallback(
async function* () {
if (!isLoggedIn || !client) return;
try {
const users = getOrThrow(await auth.getAllUsers());
// Make sure that every user has at least a black frame
for (const { username } of users) {
yield { username, frame: new Uint8Array(LIGHTHOUSE_FRAME_BYTES) };
}
const streams = await Promise.all(
users.map(async ({ username }) => {
const stream = await client.streamModel(username);
return (async function* () {
for await (const model of stream) {
if (model.PAYL instanceof Uint8Array) {
yield { username, frame: model.PAYL };
}
}
})();
})
);
yield* mergeAsyncIterables(streams);
} catch (error) {
console.error(`Could not get user streams: ${error}`);
}
},
[isLoggedIn, client, auth]
);
// NOTE: It is important that we use `useCallback` for the consumption callback
// since otherwise every rerender will create a new function, triggering a change
// is the `useEffect` that `useAsyncIterable` uses internally, which reregisters
// a new iterator on every render. This seems to cause some kind of cyclic dependency
// that freezes the application.
const consumeUserStreams = useCallback(
async ({ username, ...userModel }: { username: string } & UserModel) => {
setUsers(({ models, active }) => ({
models: models.set(username, userModel),
active: models.has(username) ? active.add(username) : active,
}));
},
[]
);
useAsyncIterable(getUserStreams, consumeUserStreams);
const value: ModelContextValue = useMemo(
() => ({
users,
async list(path) {
const message = await client?.list(path);
return messageToResult(message);
},
async get(path) {
const message = await client?.get(path);
return messageToResult(message);
},
async getLaserMetrics() {
return (await this.get(['metrics', 'laser'])) as Result<LaserMetrics>;
},
}),
[client, users]
);
return (
<ModelContext.Provider value={value}>{children}</ModelContext.Provider>
);
}