Improve memoization API with a save/restore function. v0.0.1-alpha.8.
diff --git a/docs/docs/features/memo.md b/docs/docs/features/memo.md
index e3fc00b..ac35d5f 100644
--- a/docs/docs/features/memo.md
+++ b/docs/docs/features/memo.md
@@ -61,3 +61,39 @@
will be required. For example, you could do `"myExpensiveUtility,23"`
if your utility takes a number and is given `23`. Any scheme works, as
long as the key is unique for the request/response pair to memoize.
+
+## Storing and restoring results
+
+In some cases, you may want to store and restore results between request.
+For example, you may have a retry mechanism that generates a copy of
+the initial request upon failure. In this case, you may want to avoid
+re-doing any successful memoized tasks from the first request. Yggdrasil
+Server supports this using the following API functions:
+
+```ts title="src/index.ts"
+// Handling the initial request:
+DemoServer.handleRequest(initialRequest, async (ygg) => {
+ try {
+ return await handleRequest(ygg);
+ } catch(e) {
+ // Store the memoized results so we can use it later
+ await storeMemoizedResults(ygg.getMemoizedResults());
+ }
+}, {
+ ctx
+});
+
+// Handling the retry request:
+DemoServer.handleRequest(retryRequest, async (ygg) => {
+ return await handleRequest(ygg);
+}, {
+ ctx,
+ // Initialize the ygg context with the results we already have
+ memoizedResults: await getMemoizedResults()
+});
+```
+
+It is important to emphasize that this should only be done in the
+same short-lived context (e.g. one request/operation). Sharing results in a
+larger scope can lead to data leaks (a security issue) or stale
+results (a correctness issue).
\ No newline at end of file
diff --git a/yggdrasil/package.json b/yggdrasil/package.json
index 9a66207..1c29621 100644
--- a/yggdrasil/package.json
+++ b/yggdrasil/package.json
@@ -1,7 +1,7 @@
{
"name": "@jottocraft/yggdrasil",
"description": "A simple and flexible TypeScript library for streamlining web request handling.",
- "version": "0.0.1-alpha.7",
+ "version": "0.0.1-alpha.8",
"license": "LGPL-2.1-only",
"author": "jottocraft <[email protected]>",
"main": "lib/index.js",
diff --git a/yggdrasil/src/YggdrasilServer.ts b/yggdrasil/src/YggdrasilServer.ts
index 4fa74f7..1bb2a49 100644
--- a/yggdrasil/src/YggdrasilServer.ts
+++ b/yggdrasil/src/YggdrasilServer.ts
@@ -11,13 +11,23 @@
import { YggdrasilConduitAPI } from "~/conduitClient";
/**
- * Defines the app's context, memoization tasks, and more in one type.
+ * Defines the app's types. Currently, this only defines the app's context, but it may be extended.
*/
export type YggdrasilAppTypes = {
ctx: any;
};
/**
+ * Data passed by the app to initialize the YggdrasilServer instance.
+*/
+export type YggdrasilAppData<AppTypes extends YggdrasilAppTypes> = {
+ /** Your context data to associate with this request. */
+ ctx: AppTypes["ctx"];
+ /** If you are restoring state from another YggdrasilServer instance, pass its output from ygg.getMemoizedResults() here. */
+ memoizedResults?: unknown;
+};
+
+/**
* Memoized functions.
*/
export type YggdrasilMemoizedFunctions = {
@@ -30,6 +40,11 @@
export type YggdrasilHandler<AppTypes extends YggdrasilAppTypes> = (ygg: YggdrasilServerContext<AppTypes>) => Promise<Response>;
/**
+ * Internal storage for memoized results.
+ */
+type MemoizedResultsInternal = { [key: string]: { resolved: false; dispatcher: EventTarget; } | { resolved: true; outcome: unknown; }; }
+
+/**
* The main class for processing requests.
*/
export class YggdrasilServer<AppTypes extends YggdrasilAppTypes, ApiSpec extends YggdrasilConduitAPI = { client: unknown; context: unknown; }> {
@@ -58,7 +73,7 @@
/**
* Handles a request.
*/
- async handleRequest(request: Request, handler: YggdrasilHandler<AppTypes>, app: { ctx: AppTypes["ctx"] }, options: YggdrasilServerContextOptions<AppTypes> = {}): Promise<Response> {
+ async handleRequest(request: Request, handler: YggdrasilHandler<AppTypes>, app: YggdrasilAppData<AppTypes>, options: YggdrasilServerContextOptions<AppTypes> = {}): Promise<Response> {
const url = new URL(request.url);
const baseURL = options.baseURL ? new URL(options.baseURL) : undefined;
@@ -92,7 +107,7 @@
relativePath = normalizedPath;
}
- const memoizedResults: { [key: string]: { resolved: false; dispatcher: EventTarget; } | { resolved: true; outcome: unknown; }; } = {};
+ const memoizedResults: MemoizedResultsInternal = (app.memoizedResults as MemoizedResultsInternal) ?? {};
const ygg: YggdrasilServerContext<AppTypes> = {
status(...args) {
@@ -172,6 +187,17 @@
},
hasMemoizedResult: (key) => {
return Boolean(memoizedResults[key]?.resolved);
+ },
+ getMemoizedResults: () => {
+ const completedResults: MemoizedResultsInternal = {};
+
+ for (const result in memoizedResults) {
+ if (memoizedResults[result].resolved) {
+ completedResults[result] = memoizedResults[result];
+ }
+ }
+
+ return completedResults;
}
};
diff --git a/yggdrasil/src/context.ts b/yggdrasil/src/context.ts
index 07303d1..81dfe88 100644
--- a/yggdrasil/src/context.ts
+++ b/yggdrasil/src/context.ts
@@ -70,6 +70,11 @@
memoize: <T>(key: string, task: () => Promise<T>) => Promise<T>;
/** Returns true if the requested task has been completed and its result is immediately available. */
hasMemoizedResult: (key: string) => boolean;
+ /**
+ * Returns stored memoized results. Useful if you need to save/restore state without redoing memoized work.
+ * Restore only via handleRequest's memoizedResults app option. The format of the returned value is opaque and subject to change.
+ */
+ getMemoizedResults: () => unknown;
};
export type YggdrasilRouterContext<AppTypes extends YggdrasilAppTypes> = YggdrasilServerContext<AppTypes> & {