Skip to content

Commit

Permalink
Revert "feat: cache responses (#16)"
Browse files Browse the repository at this point in the history
This reverts commit e2ff139.
  • Loading branch information
AlCalzone committed Sep 8, 2022
1 parent c23303f commit 0f2bc48
Show file tree
Hide file tree
Showing 10 changed files with 72 additions and 379 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@
"eslint": "^8.23.0",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-prettier": "^4.2.1",
"miniflare": "~2.8.1",
"miniflare": "~2.7.1",
"prettier": "^2.7.1",
"prettier-plugin-organize-imports": "^3.1.1",
"typescript": "~4.7.4",
Expand Down
54 changes: 0 additions & 54 deletions src/lib/cache.ts

This file was deleted.

2 changes: 1 addition & 1 deletion src/lib/fs/filesystem.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
export interface FileSystem {
writeFile(
file: string,
data: string | ArrayBuffer | ArrayBufferView | Blob
data: string | ReadableStream | ArrayBuffer | ArrayBufferView | Blob
): Promise<void>;
readFile(file: string): Promise<string>;
// deleteFile(file: string): Promise<void>;
Expand Down
56 changes: 49 additions & 7 deletions src/lib/shared.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { error } from "itty-router-extras";

export const hexKeyRegex4Digits = /^0x[a-f0-9]{4}$/;
export const hexKeyRegex2Digits = /^0x[a-f0-9]{2}$/;
export const firmwareVersionRegex = /^\d{1,3}\.\d{1,3}$/;
Expand Down Expand Up @@ -47,13 +49,6 @@ export function padVersion(version: string): string {
return version + ".0";
}

// expands object types recursively
export type ExpandRecursively<T> = T extends object
? T extends infer O
? { [K in keyof O]: ExpandRecursively<O[K]> }
: never
: T;

export function array2hex(arr: Uint8Array): string {
return [...arr].map((x) => x.toString(16).padStart(2, "0")).join("");
}
Expand All @@ -66,3 +61,50 @@ export function hex2array(hex: string): Uint8Array {
}
return ret;
}

/** Constant-time string comparison */
export function safeCompare(expected: string, actual: string): boolean {
const lenExpected = expected.length;
let result = 0;

if (lenExpected !== actual.length) {
actual = expected;
result = 1;
}

for (let i = 0; i < lenExpected; i++) {
result |= expected.charCodeAt(i) ^ actual.charCodeAt(i);
}

return result === 0;
}

// expands object types recursively
export type ExpandRecursively<T> = T extends object
? T extends infer O
? { [K in keyof O]: ExpandRecursively<O[K]> }
: never
: T;

export function clientError(
message: BodyInit | Record<string, any> | undefined,
code: number = 400
): Response {
return error(code, message);
}

export function serverError(
message: BodyInit | Record<string, any>,
code: number = 500
): Response {
return error(code, message);
}

export type RequestWithProps<
U extends Record<string, unknown>[],
T extends Request = Request
> = U extends [infer First, ...infer Rest extends Record<string, unknown>[]]
? RequestWithProps<Rest, T & First>
: T;

export type ContentProps = { content: unknown };
41 changes: 0 additions & 41 deletions src/lib/shared_cloudflare.ts

This file was deleted.

4 changes: 2 additions & 2 deletions src/routes/admin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@ import {
import type { RateLimiterProps } from "../durable_objects/RateLimiter";
import { encryptAPIKey } from "../lib/apiKeys";
import { createCachedR2FS, getFilesVersion } from "../lib/fs/cachedR2FS";
import { hex2array } from "../lib/shared";
import {
clientError,
ContentProps,
hex2array,
safeCompare,
type RequestWithProps,
} from "../lib/shared_cloudflare";
} from "../lib/shared";
import { uploadSchema } from "../lib/uploadSchema";
import type { CloudflareEnvironment } from "../worker";

Expand Down
51 changes: 14 additions & 37 deletions src/routes/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,14 @@ import { withDurables } from "itty-durable";
import { json, type ThrowableRouter } from "itty-router-extras";
import { APIv1_RequestSchema } from "../apiV1";
import type { RateLimiterProps } from "../durable_objects/RateLimiter";
import { withCache } from "../lib/cache";
import { lookupConfig } from "../lib/config";
import { createCachedR2FS, getFilesVersion } from "../lib/fs/cachedR2FS";
import {
clientError,
ContentProps,
serverError,
type RequestWithProps,
} from "../lib/shared_cloudflare";
} from "../lib/shared";
import { APIKeyProps, withAPIKey } from "../middleware/withAPIKey";
import type { CloudflareEnvironment } from "../worker";

Expand Down Expand Up @@ -52,8 +51,7 @@ export default function register(router: ThrowableRouter): void {
"/api/v1/updates",
async (
req: RequestWithProps<[ContentProps]>,
env: CloudflareEnvironment,
context: ExecutionContext
env: CloudflareEnvironment
) => {
const result = await APIv1_RequestSchema.safeParseAsync(
req.content
Expand All @@ -73,42 +71,21 @@ export default function register(router: ThrowableRouter): void {
return serverError("Filesystem empty");
}

// Figure out if this info is already cached
const cacheUrl = new URL(
`/${manufacturerId}:${productType}:${productId}:${firmwareVersion}?version=${version}`,
req.url
const config = await lookupConfig(
createCachedR2FS(env.CONFIG_FILES, env.R2_CACHE, version),
"/",
manufacturerId,
productType,
productId,
firmwareVersion
);
const cacheKey = cacheUrl.toString();

return withCache(
{
req,
context,
cacheKey,
// Cache for 1 hour on the client
maxAge: 60 * 60,
// Cache for 1 day on the server.
// We use the file hash/revision as part of the cache key,
// so we can safely cache for a longer time.
sMaxAge: 60 * 60 * 24,
},
async () => {
const config = await lookupConfig(
createCachedR2FS(
env.CONFIG_FILES,
env.R2_CACHE,
version
),
"/",
manufacturerId,
productType,
productId,
firmwareVersion
);
if (!config) {
// Config not found
return json([]);
}

return json(config?.upgrades ?? []);
}
);
return json(config.upgrades);
}
);
}
3 changes: 1 addition & 2 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,7 @@
"moduleResolution": "Node",

/* Support for Cloudflare */
"types": ["@cloudflare/workers-types"],
"lib": ["ESNext"]
"types": ["@cloudflare/workers-types"]
},
"include": ["src/**/*.ts", "test/**/*.ts"]
}
4 changes: 2 additions & 2 deletions wrangler.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
name = "zwave-js-firmware-updates"
usage_model = "bundled"
# workers_dev = true
workers_dev = true
compatibility_date = "2022-08-28"

# node_compat = true
Expand Down Expand Up @@ -38,7 +38,7 @@ format = "modules"
port = 8787
watch = true

cache_persist = true
cache = false
env_path = ".env"

kv_persist = true
Expand Down
Loading

0 comments on commit 0f2bc48

Please sign in to comment.