Skip to content

Commit

Permalink
[pre-commit.ci] auto fixes from pre-commit.com hooks
Browse files Browse the repository at this point in the history
for more information, see https://pre-commit.ci
  • Loading branch information
pre-commit-ci[bot] committed Apr 28, 2023
1 parent 0ec08ec commit 713fadd
Show file tree
Hide file tree
Showing 14 changed files with 109 additions and 133 deletions.
2 changes: 1 addition & 1 deletion docs/source/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@ REST API
=============

.. openapi:: ../../jupyter_server_proxy/api.yml
:examples:
:examples:
10 changes: 4 additions & 6 deletions jupyter_server_proxy/__init__.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import traitlets

from .manager import ServerProxyAppManager
from .api import setup_api_handlers
from .config import ServerProxy as ServerProxyConfig
from .config import get_entrypoint_server_processes, make_handlers, make_server_process
from .handlers import setup_handlers
from .api import setup_api_handlers
from .manager import ServerProxyAppManager


# Jupyter Extension points
Expand Down Expand Up @@ -41,9 +41,7 @@ def _load_jupyter_server_extension(nbapp):
base_url = nbapp.web_app.settings["base_url"]

# Add server_proxy_manager trait to ServerApp and Instantiate a manager
nbapp.add_traits(
server_proxy_manager=traitlets.Instance(ServerProxyAppManager)
)
nbapp.add_traits(server_proxy_manager=traitlets.Instance(ServerProxyAppManager))
manager = nbapp.server_proxy_manager = ServerProxyAppManager()
serverproxy_config = ServerProxyConfig(parent=nbapp)

Expand All @@ -52,7 +50,7 @@ def _load_jupyter_server_extension(nbapp):
nbapp.io_loop.call_later(
serverproxy_config.monitor_interval,
manager.monitor,
serverproxy_config.monitor_interval
serverproxy_config.monitor_interval,
)
except AttributeError:
nbapp.log.debug(
Expand Down
17 changes: 8 additions & 9 deletions jupyter_server_proxy/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,9 @@ async def delete(self, name):
"""Delete a server proxy by name"""
if not name:
raise web.HTTPError(
403, "Please set the name of a running server proxy that "
"user wishes to terminate"
403,
"Please set the name of a running server proxy that "
"user wishes to terminate",
)

try:
Expand All @@ -84,10 +85,8 @@ async def get(self, name):
if name:
apps = self.manager.get_server_proxy_app(name)._asdict()
# If no server proxy found this will be a dict with empty values
if not apps['name']:
raise web.HTTPError(
404, f"Server proxy {name} not found"
)
if not apps["name"]:
raise web.HTTPError(404, f"Server proxy {name} not found")
else:
apps = [app._asdict() for app in self.manager.list_server_proxy_apps()]

Expand Down Expand Up @@ -121,8 +120,8 @@ def setup_api_handlers(web_app, manager, server_processes):
(
ujoin(base_url, r"server-proxy/api/servers/(?P<name>.*)"),
ServersAPIHandler,
{"manager": manager}
{"manager": manager},
),
] + icon_handlers
]
+ icon_handlers,
)

1 change: 0 additions & 1 deletion jupyter_server_proxy/api.yml
Original file line number Diff line number Diff line change
Expand Up @@ -124,4 +124,3 @@ components:
type: string
unix_socket:
type: string

6 changes: 2 additions & 4 deletions jupyter_server_proxy/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,9 @@
from importlib.metadata import entry_points

from jupyter_server.utils import url_path_join as ujoin
from traitlets import Dict, List, Tuple, Union, Int, default, observe
from traitlets import Dict, Int, List, Tuple, Union, default, observe
from traitlets.config import Configurable

from jupyter_server.utils import url_path_join as ujoin

from .handlers import AddSlashHandler, NamedLocalProxyHandler, SuperviseAndProxyHandler

try:
Expand Down Expand Up @@ -351,5 +349,5 @@ def _host_whitelist_deprecated(self, change):
polling the status of running servers with a frequency set by this
interval.
""",
config=True
config=True,
)
49 changes: 16 additions & 33 deletions jupyter_server_proxy/manager.py
Original file line number Diff line number Diff line change
@@ -1,35 +1,18 @@
"""Manager for jupyter server proxy"""

import asyncio

from collections import namedtuple

from traitlets import List, Int
from traitlets.config import LoggingConfigurable

from jupyter_server.utils import url_path_join as ujoin

from traitlets import Int, List
from traitlets.config import LoggingConfigurable

ServerProxy = namedtuple(
"ServerProxy",
[
"name",
"url",
"cmd",
"port",
"managed",
"unix_socket"
],
defaults=[""] * 6
)
ServerProxyProc = namedtuple(
"ServerProxyProc",
[
"name",
"proc"
],
defaults=[""] * 2
["name", "url", "cmd", "port", "managed", "unix_socket"],
defaults=[""] * 6,
)
ServerProxyProc = namedtuple("ServerProxyProc", ["name", "proc"], defaults=[""] * 2)


class ServerProxyAppManager(LoggingConfigurable):
Expand All @@ -38,17 +21,12 @@ class ServerProxyAppManager(LoggingConfigurable):
by jupyter server proxy.
"""

server_proxy_apps = List(
help="List of server proxy apps"
)
server_proxy_apps = List(help="List of server proxy apps")

_server_proxy_procs = List(
help="List of server proxy app proc objects"
)
_server_proxy_procs = List(help="List of server proxy app proc objects")

num_active_server_proxy_apps = Int(
0,
help="Total number of currently running proxy apps"
0, help="Total number of currently running proxy apps"
)

def add_server_proxy_app(self, name, base_url, cmd, port, proc, unix_socket):
Expand All @@ -63,7 +41,7 @@ def add_server_proxy_app(self, name, base_url, cmd, port, proc, unix_socket):
cmd=" ".join(cmd),
port=port,
managed=True if proc else False,
unix_socket=unix_socket if unix_socket is not None else ''
unix_socket=unix_socket if unix_socket is not None else "",
)
)

Expand All @@ -89,11 +67,16 @@ def del_server_proxy_app(self, name):

def get_server_proxy_app(self, name):
"""Get a given server proxy app"""
return next((app for app in self.server_proxy_apps if app.name == name), ServerProxy())
return next(
(app for app in self.server_proxy_apps if app.name == name), ServerProxy()
)

def _get_server_proxy_proc(self, name):
"""Get a given server proxy app"""
return next((app for app in self._server_proxy_procs if app.name == name), ServerProxyProc())
return next(
(app for app in self._server_proxy_procs if app.name == name),
ServerProxyProc(),
)

def list_server_proxy_apps(self):
"""List all active server proxy apps"""
Expand Down
2 changes: 0 additions & 2 deletions jupyter_server_proxy/utils.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import os

from traitlets import TraitType


Expand Down
26 changes: 13 additions & 13 deletions labextension/schema/add-launcher-entries.json
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
{
"title": "Jupyter Server Proxy",
"description": "Jupyter Server Proxy Manager settings",
"properties": {
"refreshInterval": {
"type": "number",
"title": "Auto-refresh rate",
"description": "Time to wait (in ms) in between auto refreshes of server proxy applications",
"default": 10000
}
},
"additionalProperties": false,
"type": "object"
}
"title": "Jupyter Server Proxy",
"description": "Jupyter Server Proxy Manager settings",
"properties": {
"refreshInterval": {
"type": "number",
"title": "Auto-refresh rate",
"description": "Time to wait (in ms) in between auto refreshes of server proxy applications",
"default": 10000
}
},
"additionalProperties": false,
"type": "object"
}
22 changes: 14 additions & 8 deletions labextension/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ import {
import { ILauncher } from "@jupyterlab/launcher";
import { PageConfig, URLExt } from "@jupyterlab/coreutils";
import { IRunningSessionManagers } from "@jupyterlab/running";
import { ISettingRegistry } from '@jupyterlab/settingregistry';
import { ITranslator, TranslationBundle } from '@jupyterlab/translation';
import { ISettingRegistry } from "@jupyterlab/settingregistry";
import { ITranslator, TranslationBundle } from "@jupyterlab/translation";
import { IFrame, MainAreaWidget, WidgetTracker } from "@jupyterlab/apputils";
import { ServerProxyManager } from "./manager";
import { IModel as IServerProxyModel } from "./serverproxy";
Expand Down Expand Up @@ -48,7 +48,7 @@ function addRunningSessionManager(
managers: IRunningSessionManagers,
app: JupyterFrontEnd,
manager: ServerProxyManager,
trans: TranslationBundle
trans: TranslationBundle,
): void {
managers.add({
name: "Server Proxy Apps",
Expand All @@ -59,8 +59,9 @@ function addRunningSessionManager(
shutdownAll: () => manager.shutdownAll(),
refreshRunning: () => manager.refreshRunning(),
runningChanged: manager.runningChanged,
shutdownAllConfirmationText:
trans.__("Are you sure you want to close all server proxy applications?")
shutdownAllConfirmationText: trans.__(
"Are you sure you want to close all server proxy applications?",
),
});
}

Expand All @@ -78,15 +79,17 @@ async function activate(
translator: ITranslator,
sessions: IRunningSessionManagers | null,
): Promise<void> {
const trans = translator.load('jupyter-server-proxy');
const trans = translator.load("jupyter-server-proxy");

// Fetch configured server processes from {base_url}/server-proxy/servers-info
const response = await fetch(
URLExt.join(PageConfig.getBaseUrl(), "server-proxy/api/servers-info"),
);
if (!response.ok) {
console.log(
trans.__("Could not fetch metadata about registered servers. Make sure jupyter-server-proxy is installed."),
trans.__(
"Could not fetch metadata about registered servers. Make sure jupyter-server-proxy is installed.",
),
);
console.log(response);
return;
Expand Down Expand Up @@ -166,7 +169,10 @@ async function activate(
continue;
}

const url = URLExt.join(PageConfig.getBaseUrl(), server_process.launcher_entry.path_info);
const url = URLExt.join(
PageConfig.getBaseUrl(),
server_process.launcher_entry.path_info,
);
const title = server_process.launcher_entry.title;
const newBrowserTab = server_process.new_browser_tab;
const id = namespace + ":" + server_process.name;
Expand Down
20 changes: 12 additions & 8 deletions labextension/src/manager.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { Signal, ISignal } from "@lumino/signaling";
import { Poll } from '@lumino/polling';
import { ISettingRegistry } from '@jupyterlab/settingregistry';
import { Poll } from "@lumino/polling";
import { ISettingRegistry } from "@jupyterlab/settingregistry";
import { ServerConnection } from "@jupyterlab/services";
import { TranslationBundle } from '@jupyterlab/translation';
import { TranslationBundle } from "@jupyterlab/translation";
import { listRunning, shutdown } from "./restapi";
import * as ServerProxyApp from "./serverproxy";

Expand All @@ -21,16 +21,18 @@ export class ServerProxyManager implements ServerProxyApp.IManager {
this._settings = settings || null;
this.serverSettings = ServerConnection.makeSettings();

const interval = settings?.get('refreshInterval').composite as number || DEFAULT_REFRESH_INTERVAL;
const interval =
(settings?.get("refreshInterval").composite as number) ||
DEFAULT_REFRESH_INTERVAL;

// Start polling with exponential backoff.
this._proxyPoll = new Poll({
factory: () => this._refreshRunning(),
frequency: {
interval: interval,
backoff: true,
max: 300 * 1000
}
max: 300 * 1000,
},
});

// Fire callback when settings are changed
Expand Down Expand Up @@ -107,7 +109,9 @@ export class ServerProxyManager implements ServerProxyApp.IManager {

// Shut down all models.
await Promise.all(
this._names.map((name) => shutdown(name, this._trans, this.serverSettings)),
this._names.map((name) =>
shutdown(name, this._trans, this.serverSettings),
),
);

// Update the list of models to clear out our state.
Expand Down Expand Up @@ -169,7 +173,7 @@ export class ServerProxyManager implements ServerProxyApp.IManager {
private _onSettingsChange(settings: ISettingRegistry.ISettings) {
this._proxyPoll.frequency = {
...this._proxyPoll.frequency,
interval: settings.composite.refreshInterval as number
interval: settings.composite.refreshInterval as number,
};
}

Expand Down
12 changes: 7 additions & 5 deletions labextension/src/restapi.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { URLExt } from "@jupyterlab/coreutils";
import { showDialog, Dialog } from '@jupyterlab/apputils';
import { showDialog, Dialog } from "@jupyterlab/apputils";
import { ServerConnection } from "@jupyterlab/services";
import { TranslationBundle } from '@jupyterlab/translation';
import { TranslationBundle } from "@jupyterlab/translation";
import { IModel } from "./serverproxy";

/**
Expand Down Expand Up @@ -52,12 +52,14 @@ export async function shutdown(
const init = { method: "DELETE" };
const response = await ServerConnection.makeRequest(url, init, settings);
if (response.status === 404) {
const msg = trans.__(`Server proxy "${name}" is not running anymore. It will be removed from this list shortly`);
const msg = trans.__(
`Server proxy "${name}" is not running anymore. It will be removed from this list shortly`,
);
console.warn(msg);
void showDialog({
title: trans.__('Warning'),
title: trans.__("Warning"),
body: msg,
buttons: [Dialog.okButton({ label : 'Dismiss'})],
buttons: [Dialog.okButton({ label: "Dismiss" })],
});
} else if (response.status === 403) {
// This request cannot be made via JupyterLab UI and hence we just throw
Expand Down
4 changes: 2 additions & 2 deletions labextension/src/running.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,14 @@ export class RunningServerProxyApp implements IRunningSessions.IRunningItem {
constructor(
model: IServerProxyModel,
manager: ServerProxyManager,
app: JupyterFrontEnd
app: JupyterFrontEnd,
) {
this._model = model;
this._manager = manager;
this._app = app;
}
open(): void {
this._app.commands.execute(CommandIDs.open, { "sp": this._model });
this._app.commands.execute(CommandIDs.open, { sp: this._model });
}
icon(): LabIcon {
return ServerProxyAppIcon;
Expand Down
2 changes: 1 addition & 1 deletion labextension/src/serverproxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export interface IModel extends JSONObject {
/**
* Proxy app managed by jupyter-server-proxy or not.
*/
readonly unix_socket: string;
readonly unix_socket: string;
}

/**
Expand Down
Loading

0 comments on commit 713fadd

Please sign in to comment.