A bit better handling of responses

This commit is contained in:
Gregory Schier
2024-02-02 13:32:06 -08:00
parent d8948bb061
commit 6c69fff27d
7 changed files with 168 additions and 120 deletions

View File

@@ -189,25 +189,29 @@ async fn cmd_grpc_bidi_streaming(
}
}
};
let event_handler = app_handle.listen_global("grpc_message_in", cb);
let event_handler =
app_handle.listen_global(format!("grpc_client_msg_{}", conn_id).as_str(), cb);
let app_handle2 = app_handle.clone();
let grpc_listen = async move {
loop {
match stream.next().await {
Some(Ok(item)) => {
let item = serde_json::to_string_pretty(&item).unwrap();
app_handle2
.emit_all("grpc_message", item)
.expect("Failed to emit");
}
Some(Err(e)) => {
error!("gRPC stream error: {:?}", e);
// TODO: Handle error
}
None => {
info!("gRPC stream closed by sender");
break;
let grpc_listen = {
let app_handle = app_handle.clone();
let conn_id = conn_id.clone();
async move {
loop {
match stream.next().await {
Some(Ok(item)) => {
let item = serde_json::to_string_pretty(&item).unwrap();
app_handle
.emit_all(format!("grpc_server_msg_{}", &conn_id).as_str(), item)
.expect("Failed to emit");
}
Some(Err(e)) => {
error!("gRPC stream error: {:?}", e);
// TODO: Handle error
}
None => {
info!("gRPC stream closed by sender");
break;
}
}
}
}
@@ -283,25 +287,29 @@ async fn cmd_grpc_server_streaming(
}
}
};
let event_handler = app_handle.listen_global("grpc_message_in", cb);
let event_handler =
app_handle.listen_global(format!("grpc_client_msg_{}", conn_id).as_str(), cb);
let app_handle2 = app_handle.clone();
let grpc_listen = async move {
loop {
match stream.next().await {
Some(Ok(item)) => {
let item = serde_json::to_string_pretty(&item).unwrap();
app_handle2
.emit_all("grpc_message", item)
.expect("Failed to emit");
}
Some(Err(e)) => {
error!("gRPC stream error: {:?}", e);
// TODO: Handle error
}
None => {
info!("gRPC stream closed by sender");
break;
let grpc_listen = {
let app_handle = app_handle.clone();
let conn_id = conn_id.clone();
async move {
loop {
match stream.next().await {
Some(Ok(item)) => {
let item = serde_json::to_string_pretty(&item).unwrap();
app_handle
.emit_all(format!("grpc_server_msg_{}", &conn_id).as_str(), item)
.expect("Failed to emit");
}
Some(Err(e)) => {
error!("gRPC stream error: {:?}", e);
// TODO: Handle error
}
None => {
info!("gRPC stream closed by sender");
break;
}
}
}
}

View File

@@ -3,6 +3,7 @@ import classNames from 'classnames';
import { format } from 'date-fns';
import type { CSSProperties, FormEvent } from 'react';
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useActiveRequestId } from '../hooks/useActiveRequestId';
import { useAlert } from '../hooks/useAlert';
import type { GrpcMessage } from '../hooks/useGrpc';
import { useGrpc } from '../hooks/useGrpc';
@@ -26,26 +27,31 @@ interface Props {
}
export function GrpcConnectionLayout({ style }: Props) {
const url = useKeyValue<string>({ namespace: 'debug', key: 'grpc_url', defaultValue: '' });
const activeRequestId = useActiveRequestId();
const url = useKeyValue<string>({
namespace: 'debug',
key: ['grpc_url', activeRequestId ?? ''],
defaultValue: '',
});
const alert = useAlert();
const service = useKeyValue<string | null>({
namespace: 'debug',
key: 'grpc_service',
key: ['grpc_service', activeRequestId ?? ''],
defaultValue: null,
});
const method = useKeyValue<string | null>({
namespace: 'debug',
key: 'grpc_method',
key: ['grpc_method', activeRequestId ?? ''],
defaultValue: null,
});
const message = useKeyValue<string>({
namespace: 'debug',
key: 'grpc_message',
key: ['grpc_message', activeRequestId ?? ''],
defaultValue: '',
});
const [activeMessage, setActiveMessage] = useState<GrpcMessage | null>(null);
const [resp, setResp] = useState<string>('');
const grpc = useGrpc(url.value ?? null);
const grpc = useGrpc(url.value ?? null, activeRequestId);
const activeMethod = useMemo(() => {
if (grpc.schema == null) return null;
@@ -105,6 +111,7 @@ export function GrpcConnectionLayout({ style }: Props) {
);
useEffect(() => {
console.log('GrpcConnectionLayout');
if (grpc.schema == null) return;
const s = grpc.schema.find((s) => s.name === service.value);
if (s == null) {
@@ -167,11 +174,10 @@ export function GrpcConnectionLayout({ style }: Props) {
)}
>
<UrlBar
id="foo"
url={url.value ?? ''}
method={null}
submitIcon={null}
forceUpdateKey="to-do"
forceUpdateKey={activeRequestId ?? ''}
placeholder="localhost:50051"
onSubmit={handleConnect}
isLoading={grpc.unary.isLoading}
@@ -231,7 +237,7 @@ export function GrpcConnectionLayout({ style }: Props) {
</div>
{!service.isLoading && !method.isLoading && (
<GrpcEditor
forceUpdateKey={[service, method].join('::')}
forceUpdateKey={activeRequestId ?? ''}
url={url.value ?? ''}
defaultValue={message.value}
onChange={message.set}
@@ -255,16 +261,16 @@ export function GrpcConnectionLayout({ style }: Props) {
<Banner color="danger" className="m-2">
{grpc.unary.error}
</Banner>
) : grpc.messages.length > 0 ? (
) : (grpc.messages.value ?? []).length > 0 ? (
<SplitLayout
name="grpc_messages2"
minHeightPx={20}
defaultRatio={0.25}
leftSlot={() => (
<div className="overflow-y-auto">
{...grpc.messages.map((m, i) => (
{...(grpc.messages.value ?? []).map((m, i) => (
<HStack
key={`${m.time.getTime()}::${m.message}::${i}`}
key={`${m.timestamp}::${m.message}::${i}`}
space={2}
onClick={() => {
if (m === activeMessage) setActiveMessage(null);
@@ -292,25 +298,29 @@ export function GrpcConnectionLayout({ style }: Props) {
: 'info'
}
/>
<div className="w-full truncate text-gray-800 text-xs">{m.message}</div>
<div className="text-gray-600 text-2xs" title={m.time.toISOString()}>
{format(m.time, 'HH:mm:ss')}
<div className="w-full truncate text-gray-800 text-2xs">{m.message}</div>
<div className="text-gray-600 text-2xs">
{format(m.timestamp, 'HH:mm:ss')}
</div>
</HStack>
))}
</div>
)}
rightSlot={() =>
activeMessage && (
<div className="grid grid-rows-[auto_minmax(0,1fr)]">
<div className="pb-3 px-2">
<Separator />
</div>
<div className="pl-2 overflow-y-auto">
<JsonAttributeTree attrValue={JSON.parse(activeMessage?.message ?? '{}')} />
</div>
</div>
)
rightSlot={
!activeMessage
? null
: () => (
<div className="grid grid-rows-[auto_minmax(0,1fr)]">
<div className="pb-3 px-2">
<Separator />
</div>
<div className="pl-2 overflow-y-auto">
<JsonAttributeTree
attrValue={JSON.parse(activeMessage?.message ?? '{}')}
/>
</div>
</div>
)
}
/>
) : resp ? (

View File

@@ -209,8 +209,6 @@ export const RequestPane = memo(function RequestPane({ style, fullHeight, classN
{activeRequest && (
<>
<UrlBar
key={activeRequest.id} // Force-reset the url bar when the active request changes
id={activeRequest.id}
url={activeRequest.url}
method={activeRequest.method}
placeholder="https://example.com"

View File

@@ -8,7 +8,7 @@ import { IconButton } from './core/IconButton';
import { Input } from './core/Input';
import { RequestMethodDropdown } from './RequestMethodDropdown';
type Props = Pick<HttpRequest, 'id' | 'url'> & {
type Props = Pick<HttpRequest, 'url'> & {
className?: string;
method: HttpRequest['method'] | null;
placeholder: string;

View File

@@ -17,7 +17,7 @@ interface SlotProps {
interface Props {
name: string;
leftSlot: (props: SlotProps) => ReactNode;
rightSlot: (props: SlotProps) => ReactNode;
rightSlot: null | ((props: SlotProps) => ReactNode);
style?: CSSProperties;
className?: string;
defaultRatio?: number;
@@ -48,33 +48,37 @@ export function SplitLayout({
`${name}_height::${useActiveWorkspaceId()}`,
);
const width = widthRaw ?? defaultRatio;
const height = heightRaw ?? defaultRatio;
let height = heightRaw ?? defaultRatio;
const [isResizing, setIsResizing] = useState<boolean>(false);
const moveState = useRef<{ move: (e: MouseEvent) => void; up: (e: MouseEvent) => void } | null>(
null,
);
if (!rightSlot) {
height = 0;
minHeightPx = 0;
}
useResizeObserver(containerRef.current, ({ contentRect }) => {
setVertical(contentRect.width < STACK_VERTICAL_WIDTH);
});
const styles = useMemo<CSSProperties>(
() => ({
const styles = useMemo<CSSProperties>(() => {
return {
...style,
gridTemplate: vertical
? `
' ${areaL.gridArea}' minmax(0,${1 - height}fr)
' ${areaD.gridArea}' 0
' ${areaR.gridArea}' minmax(${minHeightPx}px,${height}fr)
/ 1fr
`
' ${areaL.gridArea}' minmax(0,${1 - height}fr)
' ${areaD.gridArea}' 0
' ${areaR.gridArea}' minmax(${minHeightPx}px,${height}fr)
/ 1fr
`
: `
' ${areaL.gridArea} ${areaD.gridArea} ${areaR.gridArea}' minmax(0,1fr)
/ ${1 - width}fr 0 ${width}fr
`,
}),
[vertical, width, height, style],
);
' ${areaL.gridArea} ${areaD.gridArea} ${areaR.gridArea}' minmax(0,1fr)
/ ${1 - width}fr 0 ${width}fr
`,
};
}, [style, vertical, height, minHeightPx, width]);
const unsub = () => {
if (moveState.current !== null) {
@@ -142,17 +146,21 @@ export function SplitLayout({
return (
<div ref={containerRef} className={classNames(className, 'grid w-full h-full')} style={styles}>
{leftSlot({ style: areaL, orientation: vertical ? 'vertical' : 'horizontal' })}
<ResizeHandle
style={areaD}
isResizing={isResizing}
barClassName={'bg-red-300'}
className={classNames(vertical ? 'translate-y-0.5' : 'translate-x-0.5')}
onResizeStart={handleResizeStart}
onReset={handleReset}
side={vertical ? 'top' : 'left'}
justify="center"
/>
{rightSlot({ style: areaR, orientation: vertical ? 'vertical' : 'horizontal' })}
{rightSlot && (
<>
<ResizeHandle
style={areaD}
isResizing={isResizing}
barClassName={'bg-red-300'}
className={classNames(vertical ? 'translate-y-0.5' : 'translate-x-0.5')}
onResizeStart={handleResizeStart}
onReset={handleReset}
side={vertical ? 'top' : 'left'}
justify="center"
/>
{rightSlot({ style: areaR, orientation: vertical ? 'vertical' : 'horizontal' })}
</>
)}
</div>
);
}

View File

@@ -1,8 +1,9 @@
import { useMutation, useQuery } from '@tanstack/react-query';
import { invoke } from '@tauri-apps/api';
import { emit } from '@tauri-apps/api/event';
import { useState } from 'react';
import { useListenToTauriEvent } from './useListenToTauriEvent';
import type { UnlistenFn } from '@tauri-apps/api/event';
import { emit, listen } from '@tauri-apps/api/event';
import { useEffect, useRef, useState } from 'react';
import { useKeyValue } from './useKeyValue';
interface ReflectResponseService {
name: string;
@@ -11,24 +12,23 @@ interface ReflectResponseService {
export interface GrpcMessage {
message: string;
time: Date;
timestamp: string;
type: 'server' | 'client' | 'info';
}
export function useGrpc(url: string | null) {
const [messages, setMessages] = useState<GrpcMessage[]>([]);
export function useGrpc(url: string | null, requestId: string | null) {
const messages = useKeyValue<GrpcMessage[]>({
namespace: 'debug',
key: ['grpc_msgs', requestId ?? 'n/a'],
defaultValue: [],
});
const [activeConnectionId, setActiveConnectionId] = useState<string | null>(null);
const unlisten = useRef<UnlistenFn | null>(null);
useListenToTauriEvent<string>(
'grpc_message',
(event) => {
setMessages((prev) => [
...prev,
{ message: event.payload, time: new Date(), type: 'server' },
]);
},
[setMessages],
);
useEffect(() => {
setActiveConnectionId(null);
unlisten.current?.();
}, [requestId]);
const unary = useMutation<string, string, { service: string; method: string; message: string }>({
mutationKey: ['grpc_unary', url],
@@ -51,8 +51,12 @@ export function useGrpc(url: string | null) {
mutationKey: ['grpc_server_streaming', url],
mutationFn: async ({ service, method, message }) => {
if (url === null) throw new Error('No URL provided');
setMessages([
{ type: 'client', message: JSON.stringify(JSON.parse(message)), time: new Date() },
await messages.set([
{
type: 'client',
message: JSON.stringify(JSON.parse(message)),
timestamp: new Date().toISOString(),
},
]);
const id: string = await invoke('cmd_grpc_server_streaming', {
endpoint: url,
@@ -60,6 +64,12 @@ export function useGrpc(url: string | null) {
method,
message,
});
unlisten.current = await listen(`grpc_server_msg_${id}`, async (event) => {
await messages.set((prev) => [
...prev,
{ message: event.payload as string, timestamp: new Date().toISOString(), type: 'server' },
]);
});
setActiveConnectionId(id);
},
});
@@ -78,16 +88,27 @@ export function useGrpc(url: string | null) {
method,
message,
});
setMessages([{ type: 'info', message: `Started connection ${id}`, time: new Date() }]);
messages.set([
{ type: 'info', message: `Started connection ${id}`, timestamp: new Date().toISOString() },
]);
setActiveConnectionId(id);
unlisten.current = await listen(`grpc_server_msg_${id}`, (event) => {
messages.set((prev) => [
...prev,
{ message: event.payload as string, timestamp: new Date().toISOString(), type: 'server' },
]);
});
},
});
const send = useMutation({
mutationKey: ['grpc_send', url],
mutationFn: async ({ message }: { message: string }) => {
await emit('grpc_message_in', { Message: message });
setMessages((m) => [...m, { type: 'client', message, time: new Date() }]);
if (activeConnectionId == null) throw new Error('No active connection');
await messages.set((m) => {
return [...m, { type: 'client', message, timestamp: new Date().toISOString() }];
});
await emit(`grpc_client_msg_${activeConnectionId}`, { Message: message });
},
});
@@ -95,10 +116,11 @@ export function useGrpc(url: string | null) {
mutationKey: ['grpc_cancel', url],
mutationFn: async () => {
setActiveConnectionId(null);
unlisten.current?.();
await emit('grpc_message_in', 'Cancel');
setMessages((m) => [
await messages.set((m) => [
...m,
{ type: 'info', message: 'Cancelled by client', time: new Date() },
{ type: 'info', message: 'Cancelled by client', timestamp: new Date().toISOString() },
]);
},
});

View File

@@ -37,19 +37,21 @@ export function useKeyValue<T extends Object | null>({
});
const set = useCallback(
(value: ((v: T) => T) | T) => {
async (value: ((v: T) => T) | T) => {
if (typeof value === 'function') {
getKeyValue({ namespace, key, fallback: defaultValue }).then((kv) => {
mutate.mutate(value(kv));
await getKeyValue({ namespace, key, fallback: defaultValue }).then((kv) => {
const newV = value(kv);
if (newV === kv) return;
return mutate.mutateAsync(newV);
});
} else {
mutate.mutate(value);
} else if (value !== query.data) {
await mutate.mutateAsync(value);
}
},
[defaultValue, key, mutate, namespace],
[defaultValue, key, mutate, namespace, query.data],
);
const reset = useCallback(() => mutate.mutate(defaultValue), [mutate, defaultValue]);
const reset = useCallback(async () => mutate.mutateAsync(defaultValue), [mutate, defaultValue]);
return useMemo(
() => ({