diff options
| author | JP Dillingham <jp@dillingham.me> | 2022-11-16 09:37:37 -0600 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2022-11-16 09:37:37 -0600 |
| commit | 72cd1f5b6d98501efa8affa45c16c0fb7abd9a18 (patch) | |
| tree | 0535f6bb4822b6edd82ddf0a13242374699b74d2 /src | |
| parent | 538f26400b5054551456bfdd0b07382089bec8a3 (diff) | |
| parent | ea91a32c6d4d354f73de23bd1e2b8f9d6799803b (diff) | |
| download | slskd-72cd1f5b6d98501efa8affa45c16c0fb7abd9a18.tar.gz | |
Merge branch 'master' into dependabot/npm_and_yarn/src/web/loader-utils-2.0.4
Diffstat (limited to 'src')
| -rw-r--r-- | src/slskd/Relay/API/Controllers/RelayController.cs | 16 | ||||
| -rw-r--r-- | src/slskd/Relay/RelayClient.cs | 94 | ||||
| -rw-r--r-- | src/web/src/components/App.js | 215 | ||||
| -rw-r--r-- | src/web/src/lib/relay.js | 9 |
4 files changed, 215 insertions, 119 deletions
diff --git a/src/slskd/Relay/API/Controllers/RelayController.cs b/src/slskd/Relay/API/Controllers/RelayController.cs index 8898e991..952507ad 100644 --- a/src/slskd/Relay/API/Controllers/RelayController.cs +++ b/src/slskd/Relay/API/Controllers/RelayController.cs @@ -47,6 +47,22 @@ namespace slskd.Relay private ILogger Log { get; } = Serilog.Log.ForContext<RelayController>(); private IRelayService Relay { get; } + [HttpPut("")] + [Authorize(Policy = AuthPolicy.Any)] + public async Task<IActionResult> Connect() + { + await Relay.Client.StartAsync(); + return Ok(); + } + + [HttpDelete("")] + [Authorize(Policy = AuthPolicy.Any)] + public async Task<IActionResult> Disconnect() + { + await Relay.Client.StopAsync(); + return NoContent(); + } + /// <summary> /// Uploads a file. /// </summary> diff --git a/src/slskd/Relay/RelayClient.cs b/src/slskd/Relay/RelayClient.cs index 854399dd..df4a3e89 100644 --- a/src/slskd/Relay/RelayClient.cs +++ b/src/slskd/Relay/RelayClient.cs @@ -95,7 +95,8 @@ namespace slskd.Relay private ManagedState<RelayClientState> State { get; } = new(); private IShareService Shares { get; } - private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); + private SemaphoreSlim ConfigurationSyncRoot { get; } = new SemaphoreSlim(1, 1); + private SemaphoreSlim StateSyncRoot { get; } = new SemaphoreSlim(1, 1); private string LastOptionsHash { get; set; } private IOptionsMonitor<Options> OptionsMonitor { get; } private IHttpClientFactory HttpClientFactory { get; } @@ -114,56 +115,69 @@ namespace slskd.Relay /// <returns></returns> public async Task StartAsync(CancellationToken cancellationToken = default) { - var mode = OptionsMonitor.CurrentValue.Relay.Mode.ToEnum<OperationMode>(); - - if (mode != OperationMode.Agent && mode != OperationMode.Debug) + if (!StateSyncRoot.Wait(0, cancellationToken)) { - throw new InvalidOperationException($"Relay client can only be started when operation mode is {OperationMode.Agent}"); + // we're already attempting to connect, let the existing attempt handle it + return; } - StartCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - LoggedInTaskCompletionSource = new TaskCompletionSource(); - StartRequested = true; + try + { + var mode = OptionsMonitor.CurrentValue.Relay.Mode.ToEnum<OperationMode>(); - Log.Information("Attempting to connect to the relay controller {Address}", OptionsMonitor.CurrentValue.Relay.Controller.Address); + if (mode != OperationMode.Agent && mode != OperationMode.Debug) + { + throw new InvalidOperationException($"Relay client can only be started when operation mode is {OperationMode.Agent}"); + } - State.SetValue(_ => TranslateState(HubConnectionState.Connecting)); + StartCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + LoggedInTaskCompletionSource = new TaskCompletionSource(); + StartRequested = true; - // retry indefinitely - await Retry.Do( - task: () => HubConnection.StartAsync(StartCancellationTokenSource.Token), - isRetryable: (attempts, ex) => true, - onFailure: (attempts, ex) => - { - Log.Debug(ex, "Relay hub connection failure"); - Log.Warning("Failed attempt #{Attempts} to connect to relay controller: {Message}", attempts, ex.Message); - }, - maxAttempts: int.MaxValue, - maxDelayInMilliseconds: 30000, - StartCancellationTokenSource.Token); + Log.Information("Attempting to connect to the relay controller {Address}", OptionsMonitor.CurrentValue.Relay.Controller.Address); - State.SetValue(_ => TranslateState(HubConnection.State)); - Log.Information("Relay controller connection established. Awaiting authentication..."); + State.SetValue(_ => TranslateState(HubConnectionState.Connecting)); - await LoggedInTaskCompletionSource.Task; + // retry indefinitely + await Retry.Do( + task: () => HubConnection.StartAsync(StartCancellationTokenSource.Token), + isRetryable: (attempts, ex) => true, + onFailure: (attempts, ex) => + { + Log.Debug(ex, "Relay hub connection failure"); + Log.Warning("Failed attempt #{Attempts} to connect to relay controller: {Message}", attempts, ex.Message); + }, + maxAttempts: int.MaxValue, + maxDelayInMilliseconds: 30000, + StartCancellationTokenSource.Token); - LoggedIn = true; + State.SetValue(_ => TranslateState(HubConnection.State)); + Log.Information("Relay controller connection established. Awaiting authentication..."); - Log.Information("Authenticated. Uploading shares..."); + await LoggedInTaskCompletionSource.Task; - try - { - await UploadSharesAsync(); + LoggedIn = true; + + Log.Information("Authenticated. Uploading shares..."); + + try + { + await UploadSharesAsync(); + } + catch (Exception ex) + { + Log.Error(ex, ex.Message); + Log.Error("Disconnecting from the relay controller"); + await StopAsync(); + throw; + } + + Log.Information("Shares uploaded. Ready to upload files."); } - catch (Exception ex) + finally { - Log.Error(ex, ex.Message); - Log.Error("Disconnecting from the relay controller"); - await StopAsync(); - throw; + StateSyncRoot.Release(); } - - Log.Information("Shares uploaded. Ready to upload files."); } /// <summary> @@ -181,6 +195,8 @@ namespace slskd.Relay LoggedIn = false; + State.SetValue(_ => TranslateState(HubConnectionState.Disconnected)); + Log.Information("Relay controller connection disconnected"); } } @@ -423,7 +439,7 @@ namespace slskd.Relay return; } - SyncRoot.Wait(); + ConfigurationSyncRoot.Wait(); try { @@ -480,7 +496,7 @@ namespace slskd.Relay } finally { - SyncRoot.Release(); + ConfigurationSyncRoot.Release(); } } diff --git a/src/web/src/components/App.js b/src/web/src/components/App.js index ea24924a..df65bc20 100644 --- a/src/web/src/components/App.js +++ b/src/web/src/components/App.js @@ -5,6 +5,7 @@ import { ToastContainer } from 'react-toastify'; import 'react-toastify/dist/ReactToastify.css'; import * as session from '../lib/session'; +import * as relayAPI from '../lib/relay'; import { connect, disconnect } from '../lib/server'; import { urlBase } from '../config'; @@ -116,10 +117,20 @@ class App extends Component { render = () => { const { login, applicationState = {}, applicationOptions = {}, error, initialized, retriesExhausted } = this.state; - const { version = {}, server, pendingReconnect, pendingRestart, shares = {}, user } = applicationState; + const { + version = {}, + relay = {}, + server, + pendingReconnect, + pendingRestart, + shares = {}, + user, + } = applicationState; const { isUpdateAvailable, current, latest } = version; const { scanPending: pendingShareRescan } = shares; + const { mode, controller } = relay; + if (!initialized) { return <Loader active size='big'/>; } @@ -147,6 +158,51 @@ class App extends Component { /> ); } + + const ModeSpecificConnectButton = ({ mode, server, controller = {} }) => { + if (mode === 'Agent') { + const isConnected = controller?.state === 'Connected'; + const isTransitioning = ['Connecting', 'Reconnecting'].includes(controller?.state); + + return <> + <Menu.Item + onClick={() => isConnected ? relayAPI.disconnect() : relayAPI.connect()} + > + <Icon.Group className='menu-icon-group'> + <Icon + name='plug' + color={controller?.state === 'Connected' + ? 'green' + : isTransitioning ? 'yellow' : 'grey'} + /> + {!isConnected && <Icon name='close' color='red' corner='bottom right' className='menu-icon-no-shadow'/>} + </Icon.Group>Controller {controller?.state} + </Menu.Item> + </>; + } else { + return <> + {server?.isConnected && <Menu.Item + onClick={() => disconnect()} + > + <Icon.Group className='menu-icon-group'> + <Icon name='plug' color={pendingReconnect ? 'yellow' : 'green'}/> + {user?.privileges?.isPrivileged && + <Icon name='star' color='yellow' corner className='menu-icon-no-shadow'/>} + </Icon.Group>Connected + </Menu.Item>} + {(!server?.isConnected) && <Menu.Item + onClick={() => connect()} + > + <Icon.Group className='menu-icon-group'> + <Icon name='plug' color='grey'/> + <Icon name='close' color='red' corner='bottom right' className='menu-icon-no-shadow'/> + </Icon.Group>Disconnected + </Menu.Item>} + </>; + } + }; + + const isAgent = mode === 'Agent'; return ( <> @@ -164,59 +220,48 @@ class App extends Component { {version.isCanary && <Menu.Item> <Icon name='flask' color='yellow'/>Canary </Menu.Item>} - <Link to={`${urlBase}/searches`}> - <Menu.Item> - <Icon name='search'/>Search - </Menu.Item> - </Link> - <Link to={`${urlBase}/downloads`}> - <Menu.Item> - <Icon name='download'/>Downloads - </Menu.Item> - </Link> - <Link to={`${urlBase}/uploads`}> - <Menu.Item> - <Icon name='upload'/>Uploads - </Menu.Item> - </Link> - <Link to={`${urlBase}/rooms`}> - <Menu.Item> - <Icon name='comments'/>Rooms - </Menu.Item> - </Link> - <Link to={`${urlBase}/chat`}> - <Menu.Item> - <Icon name='comment'/>Chat - </Menu.Item> - </Link> - <Link to={`${urlBase}/users`}> - <Menu.Item> - <Icon name='users'/>Users - </Menu.Item> - </Link> - <Link to={`${urlBase}/browse`}> - <Menu.Item> - <Icon name='folder open'/>Browse - </Menu.Item> - </Link> + {isAgent ? <Menu.Item> + <Icon name='detective'/>Agent Mode + </Menu.Item> : + <> + <Link to={`${urlBase}/searches`}> + <Menu.Item> + <Icon name='search'/>Search + </Menu.Item> + </Link> + <Link to={`${urlBase}/downloads`}> + <Menu.Item> + <Icon name='download'/>Downloads + </Menu.Item> + </Link> + <Link to={`${urlBase}/uploads`}> + <Menu.Item> + <Icon name='upload'/>Uploads + </Menu.Item> + </Link> + <Link to={`${urlBase}/rooms`}> + <Menu.Item> + <Icon name='comments'/>Rooms + </Menu.Item> + </Link> + <Link to={`${urlBase}/chat`}> + <Menu.Item> + <Icon name='comment'/>Chat + </Menu.Item> + </Link> + <Link to={`${urlBase}/users`}> + <Menu.Item> + <Icon name='users'/>Users + </Menu.Item> + </Link> + <Link to={`${urlBase}/browse`}> + <Menu.Item> + <Icon name='folder open'/>Browse + </Menu.Item> + </Link> + </>} <Menu className='right' inverted> - {server?.isConnected && <Menu.Item - onClick={() => disconnect()} - > - <Icon.Group className='menu-icon-group'> - <Icon name='plug' color={pendingReconnect ? 'yellow' : 'green'}/> - {user?.privileges?.isPrivileged && - <Icon name='star' color='yellow' corner className='menu-icon-no-shadow'/>} - </Icon.Group>Connected - </Menu.Item>} - {(!server?.isConnected) && <Menu.Item - onClick={() => connect()} - > - <Icon.Group className='menu-icon-group'> - <Icon name='plug' color='grey'/> - <Icon name='close' color='red' corner='bottom right' className='menu-icon-no-shadow'/> - </Icon.Group>Disconnected - </Menu.Item>} + <ModeSpecificConnectButton mode={mode} server={server} controller={controller} /> {(pendingReconnect || pendingRestart || pendingShareRescan) && <Menu.Item position='right'> <Icon.Group className='menu-icon-group'> <Link to={`${urlBase}/system/info`}> @@ -271,34 +316,44 @@ class App extends Component { <Sidebar.Pusher className='app-content'> <AppContext.Provider value={{ state: applicationState, options: applicationOptions }}> <Switch> - <Route path={`${urlBase}/searches/:id?`} render={(props) => - this.withTokenCheck(<div className='view'> - <Searches - server={applicationState.server} - {...props} + {isAgent ? <> + <Route path={`${urlBase}/system/:tab?`} render={ + (props) => this.withTokenCheck( + <System {...props} state={applicationState} options={applicationOptions} /> + ) + }/> + <Redirect from='*' to={`${urlBase}/system`}/> + </> : + <> + <Route path={`${urlBase}/searches/:id?`} render={(props) => + this.withTokenCheck(<div className='view'> + <Searches + server={applicationState.server} + {...props} + /> + </div>)} /> - </div>)} - /> - <Route path={`${urlBase}/browse`} render={(props) => this.withTokenCheck(<Browse {...props}/>)}/> - <Route path={`${urlBase}/users`} render={(props) => this.withTokenCheck(<Users {...props}/>)}/> - <Route path={`${urlBase}/chat`} render={(props) => this.withTokenCheck(<Chat {...props}/>)}/> - <Route path={`${urlBase}/rooms`} render={(props) => this.withTokenCheck(<Rooms {...props}/>)}/> - <Route path={`${urlBase}/uploads`} render={ - (props) => - this.withTokenCheck(<div className='view'><Transfers {...props} direction='upload'/></div>) - }/> - <Route path={`${urlBase}/downloads`} render={ - (props) => - this.withTokenCheck(<div className='view'> - <Transfers {...props} direction='download' server={applicationState.server}/> - </div>) - }/> - <Route path={`${urlBase}/system/:tab?`} render={ - (props) => this.withTokenCheck( - <System {...props} state={applicationState} options={applicationOptions} /> - ) - }/> - <Redirect from='*' to={`${urlBase}/searches`}/> + <Route path={`${urlBase}/browse`} render={(props) => this.withTokenCheck(<Browse {...props}/>)}/> + <Route path={`${urlBase}/users`} render={(props) => this.withTokenCheck(<Users {...props}/>)}/> + <Route path={`${urlBase}/chat`} render={(props) => this.withTokenCheck(<Chat {...props}/>)}/> + <Route path={`${urlBase}/rooms`} render={(props) => this.withTokenCheck(<Rooms {...props}/>)}/> + <Route path={`${urlBase}/uploads`} render={ + (props) => + this.withTokenCheck(<div className='view'><Transfers {...props} direction='upload'/></div>) + }/> + <Route path={`${urlBase}/downloads`} render={ + (props) => + this.withTokenCheck(<div className='view'> + <Transfers {...props} direction='download' server={applicationState.server}/> + </div>) + }/> + <Route path={`${urlBase}/system/:tab?`} render={ + (props) => this.withTokenCheck( + <System {...props} state={applicationState} options={applicationOptions} /> + ) + }/> + <Redirect from='*' to={`${urlBase}/searches`}/> + </>} </Switch> </AppContext.Provider> </Sidebar.Pusher> diff --git a/src/web/src/lib/relay.js b/src/web/src/lib/relay.js new file mode 100644 index 00000000..b20d0af2 --- /dev/null +++ b/src/web/src/lib/relay.js @@ -0,0 +1,9 @@ +import api from './api'; + +export const connect = () => { + return api.put('/relay'); +}; + +export const disconnect = () => { + return api.delete('/relay'); +};
\ No newline at end of file |
