Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Changes to integrate rate-limit headers for Commands left component UI #67

Merged
merged 20 commits into from
Oct 18, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions apps/playground-web/components/CLI/CLI.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,18 @@
import { useCli } from './hooks/useCli';

interface CliProps {
decreaseCommandsLeft: () => void;
onCommandExecuted: (commandsLeft: number, cleanupTimeLeft: number) => void;
}

export default function Cli({ decreaseCommandsLeft }: CliProps) {
export default function Cli({ onCommandExecuted }: CliProps) {
const {
handleInputChange,
handleKeyDown,
terminalRef,
inputRef,
output,
command,
} = useCli(decreaseCommandsLeft);
} = useCli(onCommandExecuted);
return (
<div
ref={terminalRef}
Expand Down
5 changes: 2 additions & 3 deletions apps/playground-web/components/CLI/hooks/useCli.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { useState, useEffect, useRef, KeyboardEvent, ChangeEvent } from 'react';
import { handleCommand } from '@/shared/utils/cliUtils';
import blocklistedCommands from '@/shared/utils/blocklist'; // Assuming you added blocklist here

export const useCli = (decreaseCommandsLeft: () => void) => {
export const useCli = (onCommandExecuted: (commandsLeft: number, cleanupTimeLeft: number) => void) => {
// states
const [command, setCommand] = useState('');
const [output, setOutput] = useState<string[]>([]);
Expand All @@ -27,11 +27,10 @@ export const useCli = (decreaseCommandsLeft: () => void) => {
`(error) ERR unknown command '${commandName}'`,
]);
} else {
handleCommand({ command, setOutput }); // Execute if not blocklisted
handleCommand({ command, setOutput, onCommandExecuted }); // Execute if not blocklisted
}

setCommand(''); // Clear input
decreaseCommandsLeft(); // Call to update remaining commands
};

useEffect(() => {
Expand Down
18 changes: 10 additions & 8 deletions apps/playground-web/components/Playground/TerminalUI.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
import { Dice1, Dice3, Dice5, Info } from 'lucide-react';
import Shell from '../Shell/Shell';
import { formatTime } from '@/shared/utils/commonUtils';
import { useTimer } from '@/shared/hooks/useTimer';

Check warning on line 4 in apps/playground-web/components/Playground/TerminalUI.tsx

View workflow job for this annotation

GitHub Actions / Build and Test

'useTimer' is defined but never used
import { useState } from 'react';
import Tooltip from '../Overlays/Tooltip';
export function TerminalUI() {
const [commandsLeft, setCommandsLeft] = useState(1000);
const decreaseCommandsLeft = () => {
setCommandsLeft((prev) => (prev > 0 ? prev - 1 : 0));
const [cleanupTimeLeft, setCleanupTimeLeft] = useState(15*60);
const handleCommandExecuted = (commands: number, cleanup: number) => {
setCommandsLeft(commands);
setCleanupTimeLeft(cleanup);
};

return (
<>
<div className="bg-gray-900 rounded-lg">
Expand All @@ -20,22 +23,21 @@
</div>
</div>
<div className="h-64 md:h-[30rem] bg-gray-100 rounded-lg overflow-hidden shadow-md">
<Shell decreaseCommandsLeft={decreaseCommandsLeft} />
<Shell onCommandExecuted={handleCommandExecuted} />
</div>
</div>
<TerminalCounter commandsLeft={commandsLeft} />
<TerminalCounter commandsLeft={commandsLeft} cleanupTimeLeft={cleanupTimeLeft} />
</>
);
}

function TerminalCounter({ commandsLeft }: { commandsLeft: number }) {
const { timeLeft } = useTimer(15 * 60);
function TerminalCounter({ commandsLeft, cleanupTimeLeft }: { commandsLeft: number; cleanupTimeLeft: number }) {
return (
<div className="flex flex-col">
<div className="flex flex-row justify-between text-gray-900 mt-4">
<div className="flex flex-row items-center space-x-2">
<div className="flex items-center justify-between border border-gray-400 text-sm bg-transparent p-3 rounded-lg">
<span>Cleanup in: {formatTime(timeLeft)} mins</span>
<span>Cleanup in: {formatTime(cleanupTimeLeft)} mins</span>
</div>
<Tooltip message="The time remaining until cleanup is initiated." />
</div>
Expand All @@ -56,4 +58,4 @@
</div>
</div>
);
}
}
6 changes: 3 additions & 3 deletions apps/playground-web/components/Shell/Shell.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,18 @@
import { useShell } from './hooks/useShell';

interface ShellProps {
decreaseCommandsLeft: () => void;
onCommandExecuted: (commandsLeft: number, cleanupTimeLeft: number) => void;
}

export default function Shell({ decreaseCommandsLeft }: ShellProps) {
export default function Shell({ onCommandExecuted }: ShellProps) {
const {
handleInputChange,
handleKeyDown,
terminalRef,
inputRef,
output,
command,
} = useShell(decreaseCommandsLeft);
} = useShell(onCommandExecuted);
return (
<div
ref={terminalRef}
Expand Down
5 changes: 2 additions & 3 deletions apps/playground-web/components/Shell/hooks/useShell.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { useState, useEffect, useRef, KeyboardEvent, ChangeEvent } from 'react';
import { handleCommand } from '@/shared/utils/shellUtils';
import blocklistedCommands from '@/shared/utils/blocklist';

export const useShell = (decreaseCommandsLeft: () => void) => {
export const useShell = (onCommandExecuted: (commandsLeft: number, cleanupTimeLeft: number) => void) => {
// states
const [command, setCommand] = useState('');
const [output, setOutput] = useState<string[]>([]);
Expand All @@ -32,11 +32,10 @@ export const useShell = (decreaseCommandsLeft: () => void) => {
`(error) ERR unknown command '${commandName}'`,
]);
} else {
handleCommand({ command, setOutput }); // Execute if not blocklisted
handleCommand({ command, setOutput, onCommandExecuted }); // Execute if not blocklisted
}

setCommand(''); // Clear input
decreaseCommandsLeft(); // Call to update remaining commands
};

useEffect(() => {
Expand Down
8 changes: 4 additions & 4 deletions apps/playground-web/lib/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@ export const executeShellCommandOnServer = async (
const response = await WebService.post(cmdExecURL, cmdOptions);

// Check if the response contains data or if it's an error response
if (response?.data) {
return response.data;
} else if (response?.error) {
return response.error;
if (response?.body?.data) {
return response;
} else if (response?.body?.error) {
return response;
} else {
throw new Error('Unexpected response structure');
}
Expand Down
18 changes: 7 additions & 11 deletions apps/playground-web/services/webServices.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,19 +41,15 @@ export const WebService = {
try {
const response = await fetch(`${PLAYGROUND_MONO_URL}${url}`, options);

// If the response is not OK, check if the response contains error information
if (!response.ok) {
const errorResponse = await response.json();
if (errorResponse?.error) {
throw errorResponse.error;
} else {
throw new Error(`HTTP error! Status: ${response.status}`);
}
}
const headers = {};
response.headers.forEach((value, key) => {
headers[key] = value;
});
headers['x-ratelimit-remaining'] = 101;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why're we hardcoding this number?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This was just a temporary change, I'll remove it. It looks like chrome blocks ceratin response headers to be read by the react app, so I had to hardcode this to test it out.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've removed this change and done this corresponding change in playground-mono: https://github.com/DiceDB/playground-mono/pull/41/files

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.


// Parse the result as JSON
const result = await response.json();
return result;
const body = await response.json();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we have a type defined here? preferrably using zod schema. Idea is to ensure and catch early if there is an issue with the response.

right now, we just have a lot of any which should be avoided

return { headers: headers, body: body };
} catch (error) {
if (error instanceof Error) {
console.error(`Error with ${method} request: ${error.message}`);
Expand Down
31 changes: 26 additions & 5 deletions apps/playground-web/shared/utils/cliUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
import { executeShellCommandOnServer } from '@/lib/api';
import { CommandHandler } from '@/types';

export const handleCommand = async ({ command, setOutput }: CommandHandler) => {
export const handleCommand = async ({ command, setOutput, onCommandExecuted }: CommandHandler) => {
const newOutput = `dice > ${command}`;
let result: string;
let result: any;

Check warning on line 8 in apps/playground-web/shared/utils/cliUtils.ts

View workflow job for this annotation

GitHub Actions / Build and Test

Unexpected any. Specify a different type

const [cmd, ...args] = command.split(' ');
if (!cmd) {
Expand All @@ -26,7 +26,14 @@
const [key] = args;
const cmdOptions = { key: key };
result = await executeShellCommandOnServer(cmd, cmdOptions);
setOutput((prevOutput) => [...prevOutput, newOutput, result]);
if (result?.body?.data) {
setOutput((prevOutput) => [...prevOutput, newOutput, result?.body?.data]);
} else if (result?.body?.error) {
setOutput((prevOutput) => [...prevOutput, newOutput, result?.body?.error]);
}
const commandsLeft = result?.headers?.['x-ratelimit-remaining'];
const cleanupTimeLeft = 10;
onCommandExecuted(commandsLeft, cleanupTimeLeft);
} catch (error: unknown) {
console.error('Error executing command:', error);
result = 'Error executing command';
Expand All @@ -40,7 +47,14 @@
try {
const cmdOptions = { key: key, value: value };
result = await executeShellCommandOnServer(cmd, cmdOptions);
setOutput((prevOutput) => [...prevOutput, newOutput, result]);
if (result?.body?.data) {
setOutput((prevOutput) => [...prevOutput, newOutput, result?.body?.data]);
} else if (result?.body?.error) {
setOutput((prevOutput) => [...prevOutput, newOutput, result?.body?.error]);
}
const commandsLeft = result?.headers?.['x-ratelimit-remaining'];
const cleanupTimeLeft = 10;
onCommandExecuted(commandsLeft, cleanupTimeLeft);
} catch (error: unknown) {
console.error('Error executing command:', error);
result = 'Error executing command';
Expand All @@ -59,7 +73,14 @@
try {
const cmdOptions = { keys: [keys] };
result = await executeShellCommandOnServer(cmd, cmdOptions);
setOutput((prevOutput) => [...prevOutput, newOutput, result]);
if (result?.body?.data) {
setOutput((prevOutput) => [...prevOutput, newOutput, result?.body?.data]);
} else if (result?.body?.error) {
setOutput((prevOutput) => [...prevOutput, newOutput, result?.body?.error]);
}
const commandsLeft = result?.headers?.['x-ratelimit-remaining'];
const cleanupTimeLeft = 10;
onCommandExecuted(commandsLeft, cleanupTimeLeft);
} catch (error: unknown) {
console.error('Error executing command:', error);
result = 'Error executing command';
Expand Down
2 changes: 1 addition & 1 deletion apps/playground-web/shared/utils/commonUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@ export const formatTime = (seconds: number): string => {
const minutes = Math.floor(seconds / 60);
const remainingSeconds = seconds % 60;
return `${minutes}:${remainingSeconds < 10 ? '0' : ''}${remainingSeconds}`;
};
};
13 changes: 10 additions & 3 deletions apps/playground-web/shared/utils/shellUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
import { executeShellCommandOnServer } from '@/lib/api';
import { CommandHandler } from '@/types';

export const handleCommand = async ({ command, setOutput }: CommandHandler) => {
export const handleCommand = async ({ command, setOutput, onCommandExecuted }: CommandHandler) => {
const newOutput = `dice > ${command}`;
let result: string;
let result: any;

Check warning on line 8 in apps/playground-web/shared/utils/shellUtils.ts

View workflow job for this annotation

GitHub Actions / Build and Test

Unexpected any. Specify a different type

const [cmd, ...args] = command.split(' ');

Expand All @@ -14,7 +14,14 @@
}
try {
result = await executeShellCommandOnServer(cmd, args);
setOutput((prevOutput) => [...prevOutput, newOutput, result]);
if (result?.body?.data) {
setOutput((prevOutput) => [...prevOutput, newOutput, result?.body?.data]);
} else if (result?.body?.error) {
setOutput((prevOutput) => [...prevOutput, newOutput, result?.body?.error]);
}
const commandsLeft = result?.headers?.['x-ratelimit-remaining'];
const cleanupTimeLeft = 10;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same as above

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes, I have to fix this. waiting on this issue DiceDB/playground-mono#32

onCommandExecuted(commandsLeft, cleanupTimeLeft);
} catch (error: unknown) {
console.error('Error executing command:', error);
result = 'Error executing command';
Expand Down
1 change: 1 addition & 0 deletions apps/playground-web/types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ import * as React from 'react';
export interface CommandHandler {
command: string;
setOutput: React.Dispatch<React.SetStateAction<string[]>>;
onCommandExecuted: (commandsLeft: number, cleanupTimeLeft: number) => void;
}
Loading