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

🔑 server uses storagekeys from repoprovider #724

Merged
merged 2 commits into from
Dec 21, 2023
Merged
Show file tree
Hide file tree
Changes from all 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
4 changes: 2 additions & 2 deletions apps/simple/static/binder.html
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<!doctype html>
<!DOCTYPE html>
<html>
<head>
<title>Binder - Thebe Demo</title>
Expand Down Expand Up @@ -52,7 +52,7 @@ <h1>Simple plots using mybinder.org</h1>

fig, ax = plt.subplots()
ax.scatter(*np.random.randn(2, 100), c=np.random.randn(100))
ax.set(title="Wow, a pyhton plot on my webpage!")
ax.set(title="Wow, a python plot on my webpage!")
</pre
>
</div>
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 7 additions & 10 deletions packages/core/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import type { LiteServerConfig } from 'thebe-lite';
import type { IRenderMimeRegistry } from '@jupyterlab/rendermime';
import type { StatusEvent } from './events';
import { WELL_KNOWN_REPO_PROVIDERS, makeBinderUrls } from './url';
import { getExistingServer, makeDefaultStorageKey, saveServerInfo } from './sessions';
import { getExistingServer, saveServerInfo } from './sessions';
import {
KernelManager,
KernelSpecAPI,
Expand Down Expand Up @@ -170,11 +170,8 @@ class ThebeServer implements ServerRuntime, ServerRestAPI {
}

async clearSavedBinderSessions() {
const url = this.sessionManager?.serverSettings?.baseUrl;
if (url)
window.localStorage.removeItem(
makeDefaultStorageKey(this.config.savedSessions.storagePrefix, url),
);
const urls = this.makeBinderUrls();
window.localStorage.removeItem(urls.storageKey);
}

/**
Expand Down Expand Up @@ -306,11 +303,11 @@ class ThebeServer implements ServerRuntime, ServerRestAPI {

async checkForSavedBinderSession() {
try {
const { build } = makeBinderUrls(
const { storageKey } = makeBinderUrls(
this.config,
this.repoProviders ?? WELL_KNOWN_REPO_PROVIDERS,
);
return getExistingServer(this.config.savedSessions, build);
return getExistingServer(this.config.savedSessions, storageKey);
} catch (err: any) {
this.events.triggerError({
status: ErrorStatusEvent.error,
Expand Down Expand Up @@ -359,7 +356,7 @@ class ThebeServer implements ServerRuntime, ServerRestAPI {
// the follow function will ping the server based on the settings and only return
// non-null if the server is still alive. So highly likely that the remainder of
// the connection calls below, work.
const existingSettings = await getExistingServer(this.config.savedSessions, urls.build);
const existingSettings = await this.checkForSavedBinderSession();
if (existingSettings) {
// Connect to the existing session
const serverSettings = ServerConnection.makeSettings(existingSettings);
Expand Down Expand Up @@ -462,7 +459,7 @@ class ThebeServer implements ServerRuntime, ServerRestAPI {
});

if (this.config.savedSessions.enabled) {
saveServerInfo(this.config.savedSessions, urls.build, this.id, serverSettings);
saveServerInfo(urls.storageKey, this.id, serverSettings);
console.debug(
`thebe:server:connectToServerViaBinder Saved session for ${this.id} at ${urls.build}`,
);
Expand Down
29 changes: 10 additions & 19 deletions packages/core/src/sessions.ts
Original file line number Diff line number Diff line change
@@ -1,35 +1,27 @@
import { KernelAPI, ServerConnection } from '@jupyterlab/services';
import type { SavedSessionInfo, SavedSessionOptions, ServerSettings } from './types';

export function makeDefaultStorageKey(storagePrefix: string, url: string) {
const urlObj = new URL(url);
// ignore the query string and hash
return `${storagePrefix}-${urlObj.origin + urlObj.pathname}`;
export function removeServerInfo(storageKey: string) {
window.localStorage.removeItem(storageKey);
}

export function removeServerInfo(savedSession: Required<SavedSessionOptions>, url: string) {
window.localStorage.removeItem(makeDefaultStorageKey(savedSession.storagePrefix, url));
}

export function updateLastUsedTimestamp(savedSession: Required<SavedSessionOptions>, url: string) {
const storageKey = makeDefaultStorageKey(savedSession.storagePrefix, url);
export function updateLastUsedTimestamp(storageKey: string) {
const saved = window.localStorage.getItem(storageKey);
if (!saved) return;
const obj = JSON.parse(saved);
window.localStorage.setItem(storageKey, JSON.stringify({ ...obj, lastUsed: new Date() }));
}

export function saveServerInfo(
savedSession: Required<SavedSessionOptions>,
url: string,
storageKey: string,
id: string,
serverSettings: Required<ServerSettings>,
) {
try {
// save the current connection url+token to reuse later
const { baseUrl, token, wsUrl } = serverSettings;
window.localStorage.setItem(
makeDefaultStorageKey(savedSession.storagePrefix, url),
storageKey,
JSON.stringify({
id,
baseUrl,
Expand All @@ -46,10 +38,9 @@ export function saveServerInfo(

export async function getExistingServer(
savedSessionOptions: Required<SavedSessionOptions>,
url: string,
storageKey: string,
): Promise<SavedSessionInfo | null> {
if (!savedSessionOptions.enabled) return null;
const storageKey = makeDefaultStorageKey(savedSessionOptions.storagePrefix, url);
const storedInfoJSON = window.localStorage.getItem(storageKey);
if (storedInfoJSON == null) {
console.debug('thebe:getExistingServer No session saved in ', storageKey);
Expand Down Expand Up @@ -81,7 +72,7 @@ export async function getExistingServer(
}

// refresh lastUsed timestamp in stored info
updateLastUsedTimestamp(savedSessionOptions, existingSettings.baseUrl);
updateLastUsedTimestamp(storageKey);
console.debug(
`thebe:getExistingServer Saved binder session is valid and will be reused ${existingSettings.baseUrl}`,
);
Expand Down Expand Up @@ -119,7 +110,7 @@ export function clearAllSavedSessions(storagePrefix = 'thebe-binder') {
* @param storagePrefix
* @param url
*/
export function clearSavedSession(storagePrefix = 'thebe-binder', url = '') {
console.debug(`thebe:clearSavedSession - removing ${makeDefaultStorageKey(storagePrefix, url)}`);
window.localStorage.removeItem(makeDefaultStorageKey(storagePrefix, url));
export function clearSavedSession(storageKey: string) {
console.debug(`thebe:clearSavedSession - removing ${storageKey}`);
window.localStorage.removeItem(storageKey);
}
2 changes: 1 addition & 1 deletion packages/core/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ export interface RepoProviderSpec {
export interface BinderUrlSet {
build: string;
launch: string;
storageKey?: string;
storageKey: string;
}

export type WellKnownRepoProvider = 'git' | 'github' | 'gitlab' | 'gist';
Expand Down
7 changes: 6 additions & 1 deletion packages/core/src/url.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import type { Config } from './config';
import { makeDefaultStorageKey } from './sessions';
import type { BinderUrlSet, RepoProviderSpec } from './types';

export function makeDefaultStorageKey(storagePrefix: string, url: string) {
const urlObj = new URL(url);
// ignore the query string and hash
return `${storagePrefix}-${urlObj.origin + urlObj.pathname}`;
}

function makeDefaultBuildSpec(storagePrefix: string, binderUrl: string, stub: string) {
const build = `${binderUrl}/build/${stub}`;
const launch = `${binderUrl}/v2/${stub}`;
Expand Down
2 changes: 1 addition & 1 deletion packages/core/tests/sessions.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, test, expect } from 'vitest';
import { makeDefaultStorageKey } from '../src/sessions';
import { makeDefaultStorageKey } from '../src/url';

describe('session saving', () => {
describe('make storage key', () => {
Expand Down
2 changes: 1 addition & 1 deletion packages/thebe/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@
"@jupyter-widgets/base": "6.0.6",
"@jupyter-widgets/controls": "5.0.7",
"@jupyter-widgets/jupyterlab-manager": "5.0.9",
"thebe-core": "^0.4.0",
"thebe-core": "^0.4.4",
"codemirror": "5.61.1",
"current-script-polyfill": "^1.0.0"
},
Expand Down
Loading