Skip to content

Commit

Permalink
Optimize logic
Browse files Browse the repository at this point in the history
  • Loading branch information
qiuhaotc committed Jan 27, 2021
1 parent a8f077b commit b03fccb
Show file tree
Hide file tree
Showing 6 changed files with 34 additions and 35 deletions.
26 changes: 10 additions & 16 deletions src/WebSSH/Client/Pages/RemoteShell.razor
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@
{
if (!string.IsNullOrEmpty(response.Response.Output))
{
await WriteToConsole(response.Response.Output);
await WriteToConsole(response.Response.Output, false);

if (response.Response.Lines == Constants.MaxinumLines)
{
Expand Down Expand Up @@ -190,7 +190,7 @@
Command = string.Empty;
StaticUtils.Clear(UniqueId);
await JSRuntime.InvokeAsync<object>("ClearTerm");
currentOutputLine = 0;
currentOutputIndex = 0;
currentCommandLine = 1;
}

Expand All @@ -202,15 +202,15 @@
{
RunCommand();
}
else if(args.Key == "ArrowUp")
else if (args.Key == "ArrowUp")
{
var result = StaticUtils.GetPreCommand(UniqueId, ref currentCommandLine);
if (result.Successful)
{
Command = result.CommandStr;
}
}
else if(args.Key == "ArrowDown")
else if (args.Key == "ArrowDown")
{
var result = StaticUtils.GetNextCommand(UniqueId, ref currentCommandLine);
if (result.Successful)
Expand All @@ -220,27 +220,21 @@
}
}

int currentOutputLine;
int currentOutputIndex;

async Task WriteToConsole(string messageToWrite)
async Task WriteToConsole(string messageToWrite, bool addNewLine = true)
{
StaticUtils.AddOutputString(UniqueId, messageToWrite);
StaticUtils.AddOutputString(UniqueId, addNewLine ? (Constants.NewLineForShell + messageToWrite + Constants.NewLineForShell) : messageToWrite);

foreach (var message in StaticUtils.GetOutputString(UniqueId, ref currentOutputLine))
{
await JSRuntime.InvokeAsync<object>("WriteToTerm", message);
}
await JSRuntime.InvokeAsync<object>("WriteToTerm", StaticUtils.GetOutputString(UniqueId, ref currentOutputIndex));
}

async void WriteToConsole()
{
await JSRuntime.InvokeAsync<object>("ClearTerm");

currentOutputLine = 0;
currentOutputIndex = 0;

foreach (var message in StaticUtils.GetOutputString(UniqueId, ref currentOutputLine))
{
await JSRuntime.InvokeAsync<object>("WriteToTerm", message);
}
await JSRuntime.InvokeAsync<object>("WriteToTerm", StaticUtils.GetOutputString(UniqueId, ref currentOutputIndex));
}
}
23 changes: 11 additions & 12 deletions src/WebSSH/Client/StaticUtils.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WebSSH.Shared;

namespace WebSSH.Client
Expand All @@ -13,30 +14,28 @@ public static class StaticUtils

public static void AddOutputString(Guid uniqueKey, string message)
{
var messages = message.SplitByLines();

if (!OutputStrings.TryGetValue(uniqueKey, out var outputStrings))
{
outputStrings = new List<string>();
outputStrings = new StringBuilder();
OutputStrings.Add(uniqueKey, outputStrings);
}

outputStrings.AddRange(messages);
outputStrings.Append(message);

if (outputStrings.Count > Constants.MaxinumCachedLines)
if (outputStrings.Length > Constants.MaxinumOutputLength)
{
outputStrings.RemoveRange(0, outputStrings.Count - Constants.MaxinumCachedLines);
outputStrings.Remove(0, outputStrings.Length - Constants.MaxinumOutputLength);
}
}

public static string[] GetOutputString(Guid uniqueKey, ref int currentLine)
public static string GetOutputString(Guid uniqueKey, ref int currentIndex)
{
var outputs = OutputStrings.TryGetValue(uniqueKey, out var outputStrings) ? outputStrings : new List<string>();
var outputs = OutputStrings.TryGetValue(uniqueKey, out var outputStrings) ? outputStrings : null;

var lines = outputs.Skip(currentLine).ToArray();
currentLine += lines.Length;
var outputStr = new string(outputs?.ToString().Skip(currentIndex).ToArray() ?? Array.Empty<char>());
currentIndex += outputStr.Length;

return lines;
return outputStr;
}

public static (string CommandStr, bool Successful) GetPreCommand(Guid uniqueKey, ref int currentCommandLine)
Expand Down Expand Up @@ -104,7 +103,7 @@ public static void Clear(Guid uniqueKey)
}
}

static Dictionary<Guid, List<string>> OutputStrings { get; set; } = new();
static Dictionary<Guid, StringBuilder> OutputStrings { get; set; } = new();
static Dictionary<Guid, List<string>> Commands { get; set; } = new();

static string[] SplitByLines(this string str)
Expand Down
2 changes: 1 addition & 1 deletion src/WebSSH/Client/wwwroot/js/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ function StartTerm(id) {

function WriteToTerm(content) {
if (term !== null) {
term.writeln(content);
term.write(content);
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/WebSSH/Server/Common/ServerActiveSessionsModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public ServerActiveSessionModel Connected(ActiveSessionModel activeSessionModel,
string result = null;
while ((result = sessionModel.ShellStream.ReadLine(TimeSpan.FromSeconds(0.3))) != null)
{
outputQueue.Enqueue(result + Environment.NewLine);
outputQueue.Enqueue(result + Constants.NewLineForShell);
}

outputQueue.Enqueue(sessionModel.ShellStream.Read());
Expand All @@ -49,7 +49,7 @@ public ServerActiveSessionModel Connected(ActiveSessionModel activeSessionModel,
{
outputQueue.Enqueue(Encoding.UTF8.GetString(e.Data));

if(outputQueue.Count > Constants.MaxinumCachedLines)
if(outputQueue.Count > Constants.MaxinumQueueCount)
{
outputQueue.TryDequeue(out _);
}
Expand Down
8 changes: 5 additions & 3 deletions src/WebSSH/Server/Common/ShellPool.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public ShellPool(ShellConfiguration shellConfiguration)
foreach (var shell in ShellPoolDictionary.ToArray())
{
// Haven't access more than Max Idle Minutes or Connected Is False
var expiredShells = shell.Value.Sessions.Where(u => u.Value.StartSessionDate < DateTime.Now.AddMinutes(-shellConfiguration.MaxIdleMinutes) || !u.Value.Client.IsConnected).ToArray();
var expiredShells = shell.Value.Sessions.Where(u => u.Value.LastAccessSessionDate < DateTime.Now.AddMinutes(-shellConfiguration.MaxIdleMinutes) || !u.Value.Client.IsConnected).ToArray();

foreach (var expiredShell in expiredShells)
{
Expand Down Expand Up @@ -71,6 +71,7 @@ public void RunShellCommand(string sessionId, Guid uniqueId, string command)
}
}

serverActiveSessionModel.LastAccessSessionDate = DateTime.Now;
serverActiveSessionModel.ShellStream.WriteLine(command);
}
else
Expand All @@ -84,14 +85,15 @@ public ServerOutput GetShellOutput(string sessionId, Guid uniqueId)
if (ShellPoolDictionary.TryGetValue(sessionId, out var serverActiveSessionsModel) && serverActiveSessionsModel.Sessions.TryGetValue(uniqueId, out var serverActiveSessionModel))
{
var totalLines = 0;
var outputStringBuilder = new StringBuilder();
StringBuilder outputStringBuilder = null;
while (totalLines < Constants.MaxinumLines && serverActiveSessionModel.OutputQueue.TryDequeue(out var output))
{
totalLines++;
outputStringBuilder = outputStringBuilder ?? new StringBuilder();
outputStringBuilder.Append(output);
}

return new ServerOutput { Output = outputStringBuilder.ToString(), Lines = totalLines };
return new ServerOutput { Output = outputStringBuilder?.ToString() ?? string.Empty, Lines = totalLines };
}
else
{
Expand Down
6 changes: 5 additions & 1 deletion src/WebSSH/Shared/Constants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ public static class Constants

public const int MaxinumLines = 1000;

public const int MaxinumCachedLines = 10000;
public const int MaxinumQueueCount = 10000;

public const int MaxinumOutputLength = 100000;

public const string NewLineForShell = "\r\n";
}
}

0 comments on commit b03fccb

Please sign in to comment.