-
Notifications
You must be signed in to change notification settings - Fork 0
feat: add custom API route for .deepnote files #27
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 from all commits
7f654bc
87d62f6
689036e
83879a8
2c44ef3
16222c2
63b3519
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
This file was deleted.
This file was deleted.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,24 +1,68 @@ | ||
| from datetime import datetime | ||
| import json | ||
|
|
||
| from jupyter_server.base.handlers import APIHandler | ||
| from jupyter_server.utils import url_path_join | ||
| from jupyter_core.utils import ensure_async | ||
| import tornado | ||
|
|
||
|
|
||
| class RouteHandler(APIHandler): | ||
| # The following decorator should be present on all verb methods (head, get, post, | ||
| # patch, put, delete, options) to ensure only authorized user can request the | ||
| # Jupyter server | ||
| @tornado.web.authenticated | ||
| def get(self): | ||
| self.finish(json.dumps({ | ||
| "data": "This is /jupyterlab-deepnote/get-example endpoint!" | ||
| })) | ||
| async def get(self): | ||
| path = self.get_query_argument("path", default=None) | ||
| if not path: | ||
| self.set_status(400) | ||
| self.set_header("Content-Type", "application/json") | ||
| self.finish( | ||
| json.dumps( | ||
| { | ||
| "code": 400, | ||
| "message": "Missing required 'path' parameter", | ||
| } | ||
| ) | ||
| ) | ||
| return | ||
| try: | ||
| model = await ensure_async( | ||
| self.contents_manager.get( | ||
| path, type="file", format="text", content=True | ||
| ) | ||
| ) | ||
| except FileNotFoundError: | ||
| self.set_status(404) | ||
| self.set_header("Content-Type", "application/json") | ||
| self.finish(json.dumps({"code": 404, "message": "File not found"})) | ||
| return | ||
| except PermissionError: | ||
| self.set_status(403) | ||
| self.set_header("Content-Type", "application/json") | ||
| self.finish(json.dumps({"code": 403, "message": "Permission denied"})) | ||
| return | ||
| except Exception: | ||
| self.log.exception("Error retrieving file") | ||
| self.set_status(500) | ||
| self.set_header("Content-Type", "application/json") | ||
| self.finish(json.dumps({"code": 500, "message": "Internal server error"})) | ||
| return | ||
| # Convert datetimes to strings so JSON can handle them | ||
| for key in ("created", "last_modified"): | ||
| if isinstance(model.get(key), datetime): | ||
| model[key] = model[key].isoformat() | ||
|
|
||
| # Return everything, including YAML content | ||
| result = {"deepnoteFileModel": model} | ||
|
|
||
| self.finish(json.dumps(result)) | ||
andyjakubowski marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
|
|
||
| def setup_handlers(web_app): | ||
| host_pattern = ".*$" | ||
|
|
||
| base_url = web_app.settings["base_url"] | ||
| route_pattern = url_path_join(base_url, "jupyterlab-deepnote", "get-example") | ||
| route_pattern = url_path_join(base_url, "jupyterlab-deepnote", "file") | ||
| handlers = [(route_pattern, RouteHandler)] | ||
| web_app.add_handlers(host_pattern, handlers) | ||
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| @@ -1,59 +1,60 @@ | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| import { Contents, RestContentProvider } from '@jupyterlab/services'; | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| import { z } from 'zod'; | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| import { transformDeepnoteYamlToNotebookContent } from './transform-deepnote-yaml-to-notebook-content'; | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| import { requestAPI } from './handler'; | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
coderabbitai[bot] marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| import { z } from 'zod'; | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| export const deepnoteContentProviderName = 'deepnote-content-provider'; | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| const deepnoteFileFromServerSchema = z.object({ | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| cells: z.array(z.any()), // or refine further with nbformat | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| metadata: z.object({ | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| deepnote: z.object({ | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| rawYamlString: z.string() | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| }) | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| }), | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| nbformat: z.number(), | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| nbformat_minor: z.number() | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| const deepnoteFileResponseSchema = z.object({ | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| deepnoteFileModel: z.object({ | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| name: z.string(), | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| path: z.string(), | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| created: z.string(), | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| last_modified: z.string(), | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| content: z.string(), | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| mimetype: z.string().optional() | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| }) | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| }); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Comment on lines
+8
to
17
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🧹 Nitpick | 🔵 Trivial Tighten schema (reject unknowns; validate timestamps) Make both objects strict and validate ISO‑ish timestamps to fail early on bad data. -const deepnoteFileResponseSchema = z.object({
- deepnoteFileModel: z.object({
+const deepnoteFileResponseSchema = z.object({
+ deepnoteFileModel: z
+ .object({
name: z.string(),
path: z.string(),
- created: z.string(),
- last_modified: z.string(),
+ created: z.string().refine(v => !Number.isNaN(Date.parse(v)), 'invalid datetime'),
+ last_modified: z.string().refine(v => !Number.isNaN(Date.parse(v)), 'invalid datetime'),
content: z.string(),
mimetype: z.string().optional()
- })
-});
+ })
+ .strict()
+}).strict();📝 Committable suggestion
Suggested change
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. No, that’s way too intense. What we have is sufficient.
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @andyjakubowski, understood. I'll keep the validation as-is. ✏️ Learnings added
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| export class DeepnoteContentProvider extends RestContentProvider { | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| async get( | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| localPath: string, | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| options?: Contents.IFetchOptions | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| ): Promise<Contents.IModel> { | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| const model = await super.get(localPath, options); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| const isDeepnoteFile = | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| localPath.endsWith('.deepnote') && model.type === 'notebook'; | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| const isDeepnoteFile = localPath.toLowerCase().endsWith('.deepnote'); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| if (!isDeepnoteFile) { | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| // Not a .deepnote file, return as-is | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| return model; | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| const nonDeepnoteModel = await super.get(localPath, options); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| return nonDeepnoteModel; | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| const validatedModelContent = deepnoteFileFromServerSchema.safeParse( | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| model.content | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| ); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| if (!validatedModelContent.success) { | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| console.error( | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| 'Invalid .deepnote file content:', | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| validatedModelContent.error | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| ); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| // Return an empty notebook instead of throwing an error | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| model.content.cells = []; | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| return model; | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| // Call custom API route to fetch the Deepnote file content | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| const data = await requestAPI(`file?path=${encodeURIComponent(localPath)}`); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| const parsed = deepnoteFileResponseSchema.safeParse(data); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Comment on lines
+33
to
+34
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🧹 Nitpick | 🔵 Trivial Prefer URLSearchParams for query composition Safer and clearer than manual string interpolation/encoding. -const data = await requestAPI(`file?path=${encodeURIComponent(localPath)}`);
+const params = new URLSearchParams({ path: localPath });
+const data = await requestAPI(`file?${params.toString()}`);📝 Committable suggestion
Suggested change
🤖 Prompt for AI Agents |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| if (!parsed.success) { | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| console.error('Invalid API response shape', parsed.error); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| throw new Error('Invalid API response shape'); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Comment on lines
+35
to
38
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🧹 Nitpick | 🔵 Trivial Include path in error to aid debugging Surface which file failed and keep the zod error in logs. -if (!parsed.success) {
- console.error('Invalid API response shape', parsed.error);
- throw new Error('Invalid API response shape');
-}
+if (!parsed.success) {
+ const msg = `Invalid API response shape for ${localPath}`;
+ console.error(msg, parsed.error);
+ throw new Error(msg);
+}📝 Committable suggestion
Suggested change
🤖 Prompt for AI Agents |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| const modelData = parsed.data.deepnoteFileModel; | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| // Transform the Deepnote YAML to Jupyter notebook content | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| const transformedModelContent = | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| await transformDeepnoteYamlToNotebookContent( | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| validatedModelContent.data.metadata.deepnote.rawYamlString | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| ); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| const transformedModel = { | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| ...model, | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| content: transformedModelContent | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| const notebookContent = await transformDeepnoteYamlToNotebookContent( | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| modelData.content | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| ); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| const model: Contents.IModel = { | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| name: modelData.name, | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| path: modelData.path, | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| type: 'notebook', | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| writable: false, | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| created: modelData.created, | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| last_modified: modelData.last_modified, | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| mimetype: 'application/x-ipynb+json', | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| format: 'json', | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| content: notebookContent | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| }; | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Comment on lines
41
to
56
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🧹 Nitpick | 🔵 Trivial Respect options.content to avoid unnecessary heavy transforms Skip YAML→notebook conversion and omit content/mime/format when content isn’t requested. -// Transform the Deepnote YAML to Jupyter notebook content
-const notebookContent = await transformDeepnoteYamlToNotebookContent(
- modelData.content
-);
+// Respect options?.content === false to avoid heavy transform
+const wantContent = options?.content !== false;
+const notebookContent = wantContent
+ ? await transformDeepnoteYamlToNotebookContent(modelData.content)
+ : null;
@@
- mimetype: 'application/x-ipynb+json',
- format: 'json',
+ mimetype: wantContent ? 'application/x-ipynb+json' : null,
+ format: wantContent ? 'json' : null,
content: notebookContent📝 Committable suggestion
Suggested change
🤖 Prompt for AI Agents |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| return transformedModel; | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| return model; | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Uh oh!
There was an error while loading. Please reload this page.