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

DX-1660: add EVAL_RO and EVALSHA_RO commands #1365

Merged
merged 2 commits into from
Mar 26, 2025
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: 3 additions & 1 deletion pkg/auto-pipeline.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,9 @@ describe("Auto pipeline", () => {
redis.decrby(newKey(), 1),
redis.del(newKey()),
redis.echo("hello"),
redis.evalRo("return ARGV[1]", [], ["Hello"]),
redis.eval("return ARGV[1]", [], ["Hello"]),
redis.evalshaRo(scriptHash, [], ["Hello"]),
redis.evalsha(scriptHash, [], ["Hello"]),
redis.exists(newKey()),
redis.expire(newKey(), 5),
Expand Down Expand Up @@ -149,7 +151,7 @@ describe("Auto pipeline", () => {
redis.json.arrappend(persistentKey3, "$.log", '"three"'),
]);
expect(result).toBeTruthy();
expect(result.length).toBe(122); // returns
expect(result.length).toBe(124); // returns
// @ts-expect-error pipelineCounter is not in type but accessible120 results
expect(redis.pipelineCounter).toBe(1);
});
Expand Down
41 changes: 41 additions & 0 deletions pkg/commands/evalRo.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { EvalROCommand } from "./evalRo";

import { keygen, newHttpClient, randomID } from "../test-utils";

import { afterAll, describe, expect, test } from "bun:test";
import { SetCommand } from "./set";
const client = newHttpClient();

const { newKey, cleanup } = keygen();
afterAll(cleanup);

describe("without keys", () => {
test("returns something", async () => {
const value = randomID();
const res = await new EvalROCommand(["return ARGV[1]", [], [value]]).exec(client);
expect(res).toEqual(value);
});
});

describe("with keys", () => {
test("returns something", async () => {
const value = randomID();
const key = newKey();
await new SetCommand([key, value]).exec(client);
const res = await new EvalROCommand([`return redis.call("GET", KEYS[1])`, [key], []]).exec(
client
);
expect(res).toEqual(value);
});
});

describe("with keys and write commands", () => {
test("throws", async () => {
const value = randomID();
const key = newKey();
await new SetCommand([key, value]).exec(client);
expect(async () => {
await new EvalROCommand([`return redis.call("DEL", KEYS[1])`, [key], []]).exec(client);
}).toThrow();
});
});
14 changes: 14 additions & 0 deletions pkg/commands/evalRo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import type { CommandOptions } from "./command";
import { Command } from "./command";

/**
* @see https://redis.io/commands/eval_ro
*/
export class EvalROCommand<TArgs extends unknown[], TData> extends Command<unknown, TData> {
constructor(
[script, keys, args]: [script: string, keys: string[], args: TArgs],
opts?: CommandOptions<unknown, TData>
) {
super(["eval_ro", script, keys.length, ...keys, ...(args ?? [])], opts);
}
}
43 changes: 43 additions & 0 deletions pkg/commands/evalshaRo.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { keygen, newHttpClient, randomID } from "../test-utils";

import { afterAll, describe, expect, test } from "bun:test";
import { EvalshaROCommand } from "./evalshaRo";
import { ScriptLoadCommand } from "./script_load";
import { SetCommand } from "./set";

const client = newHttpClient();

const { newKey, cleanup } = keygen();
afterAll(cleanup);

describe("without keys", () => {
test("returns something", async () => {
const value = randomID();
const sha1 = await new ScriptLoadCommand([`return {ARGV[1], "${value}"}`]).exec(client);
const res = await new EvalshaROCommand([sha1, [], [value]]).exec(client);
expect(res).toEqual([value, value]);
});
});

describe("with keys", () => {
test("returns something", async () => {
const value = randomID();
const key = newKey();
await new SetCommand([key, value]).exec(client);
const sha1 = await new ScriptLoadCommand([`return redis.call("GET", KEYS[1])`]).exec(client);
const res = await new EvalshaROCommand([sha1, [key], []]).exec(client);
expect(res).toEqual(value);
});
});

describe("with keys and write commands", () => {
test("throws", async () => {
const value = randomID();
const key = newKey();
await new SetCommand([key, value]).exec(client);
const sha1 = await new ScriptLoadCommand([`return redis.call("DEL", KEYS[1])`]).exec(client);
expect(async () => {
await new EvalshaROCommand([sha1, [key], []]).exec(client);
}).toThrow();
});
});
14 changes: 14 additions & 0 deletions pkg/commands/evalshaRo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import type { CommandOptions } from "./command";
import { Command } from "./command";

/**
* @see https://redis.io/commands/evalsha_ro
*/
export class EvalshaROCommand<TArgs extends unknown[], TData> extends Command<unknown, TData> {
constructor(
[sha, keys, args]: [sha: string, keys: string[], args?: TArgs],
opts?: CommandOptions<unknown, TData>
) {
super(["evalsha_ro", sha, keys.length, ...keys, ...(args ?? [])], opts);
}
}
2 changes: 2 additions & 0 deletions pkg/commands/mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ export * from "./decr";
export * from "./decrby";
export * from "./del";
export * from "./echo";
export * from "./evalRo";
export * from "./eval";
export * from "./evalshaRo";
export * from "./evalsha";
export * from "./exec";
export * from "./exists";
Expand Down
2 changes: 2 additions & 0 deletions pkg/commands/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ export { type DecrCommand } from "./decr";
export { type DecrByCommand } from "./decrby";
export { type DelCommand } from "./del";
export { type EchoCommand } from "./echo";
export { type EvalROCommand } from "./evalRo";
export { type EvalCommand } from "./eval";
export { type EvalshaROCommand } from "./evalshaRo";
export { type EvalshaCommand } from "./evalsha";
export { type ExistsCommand } from "./exists";
export { type ExpireCommand } from "./expire";
Expand Down
4 changes: 3 additions & 1 deletion pkg/pipeline.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,9 @@ describe("use all the things", () => {
.decrby(newKey(), 1)
.del(newKey())
.echo("hello")
.evalRo("return ARGV[1]", [], ["Hello"])
.eval("return ARGV[1]", [], ["Hello"])
.evalshaRo(scriptHash, [], ["Hello"])
.evalsha(scriptHash, [], ["Hello"])
.exists(newKey())
.expire(newKey(), 5)
Expand Down Expand Up @@ -250,7 +252,7 @@ describe("use all the things", () => {
.json.set(newKey(), "$", { hello: "world" });

const res = await p.exec();
expect(res.length).toEqual(122);
expect(res.length).toEqual(124);
});
});
describe("keep errors", () => {
Expand Down
16 changes: 16 additions & 0 deletions pkg/pipeline.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ import {
DecrCommand,
DelCommand,
EchoCommand,
EvalROCommand,
EvalCommand,
EvalshaROCommand,
EvalshaCommand,
ExistsCommand,
ExpireAtCommand,
Expand Down Expand Up @@ -449,13 +451,27 @@ export class Pipeline<TCommands extends Command<any, any>[] = []> {
echo = (...args: CommandArgs<typeof EchoCommand>) =>
this.chain(new EchoCommand(args, this.commandOptions));

/**
* @see https://redis.io/commands/eval_ro
*/
evalRo = <TArgs extends unknown[], TData = unknown>(
...args: [script: string, keys: string[], args: TArgs]
) => this.chain(new EvalROCommand<TArgs, TData>(args, this.commandOptions));

/**
* @see https://redis.io/commands/eval
*/
eval = <TArgs extends unknown[], TData = unknown>(
...args: [script: string, keys: string[], args: TArgs]
) => this.chain(new EvalCommand<TArgs, TData>(args, this.commandOptions));

/**
* @see https://redis.io/commands/evalsha_ro
*/
evalshaRo = <TArgs extends unknown[], TData = unknown>(
...args: [sha1: string, keys: string[], args: TArgs]
) => this.chain(new EvalshaROCommand<TArgs, TData>(args, this.commandOptions));

/**
* @see https://redis.io/commands/evalsha
*/
Expand Down
53 changes: 51 additions & 2 deletions pkg/redis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ import {
DecrCommand,
DelCommand,
EchoCommand,
EvalROCommand,
EvalCommand,
EvalshaROCommand,
EvalshaCommand,
ExecCommand,
ExistsCommand,
Expand Down Expand Up @@ -183,6 +185,7 @@ import { ZMScoreCommand } from "./commands/zmscore";
import type { Requester, UpstashRequest, UpstashResponse } from "./http";
import { Pipeline } from "./pipeline";
import { Script } from "./script";
import { ScriptRO } from "./scriptRo";
import type { CommandArgs, RedisOptions, Telemetry } from "./types";

// See https://github.com/upstash/upstash-redis/issues/342
Expand Down Expand Up @@ -393,9 +396,41 @@ export class Redis {
}
};

createScript(script: string): Script {
return new Script(this, script);
/**
* Creates a new script.
*
* Scripts offer the ability to optimistically try to execute a script without having to send the
* entire script to the server. If the script is loaded on the server, it tries again by sending
* the entire script. Afterwards, the script is cached on the server.
*
* @param script - The script to create
* @param opts - Optional options to pass to the script `{ readonly?: boolean }`
* @returns A new script
*
* @example
* ```ts
* const redis = new Redis({...})
*
* const script = redis.createScript<string>("return ARGV[1];")
* const arg1 = await script.eval([], ["Hello World"])
* expect(arg1, "Hello World")
* ```
* @example
* ```ts
* const redis = new Redis({...})
*
* const script = redis.createScript<string>("return ARGV[1];", { readonly: true })
* const arg1 = await script.evalRo([], ["Hello World"])
* expect(arg1, "Hello World")
* ```
*/
createScript(script: string): Script;
createScript(script: string, opts: { readonly?: false }): Script;
createScript(script: string, opts: { readonly: true }): ScriptRO;
createScript(script: string, opts?: { readonly?: boolean }): Script | ScriptRO {
return opts?.readonly ? new ScriptRO(this, script) : new Script(this, script);
}

/**
* Create a new pipeline that allows you to send requests in bulk.
*
Expand Down Expand Up @@ -520,13 +555,27 @@ export class Redis {
echo = (...args: CommandArgs<typeof EchoCommand>) =>
new EchoCommand(args, this.opts).exec(this.client);

/**
* @see https://redis.io/commands/eval_ro
*/
evalRo = <TArgs extends unknown[], TData = unknown>(
...args: [script: string, keys: string[], args: TArgs]
) => new EvalROCommand<TArgs, TData>(args, this.opts).exec(this.client);

/**
* @see https://redis.io/commands/eval
*/
eval = <TArgs extends unknown[], TData = unknown>(
...args: [script: string, keys: string[], args: TArgs]
) => new EvalCommand<TArgs, TData>(args, this.opts).exec(this.client);

/**
* @see https://redis.io/commands/evalsha_ro
*/
evalshaRo = <TArgs extends unknown[], TData = unknown>(
...args: [sha1: string, keys: string[], args: TArgs]
) => new EvalshaROCommand<TArgs, TData>(args, this.opts).exec(this.client);

/**
* @see https://redis.io/commands/evalsha
*/
Expand Down
40 changes: 40 additions & 0 deletions pkg/scriptRo.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { afterEach, describe, expect, test } from "bun:test";
import { Redis } from "./redis";
import { keygen, newHttpClient, randomID } from "./test-utils";
const client = newHttpClient();

const { newKey, cleanup } = keygen();
afterEach(cleanup);

describe("create a new readonly script", () => {
test(
"creates a new readonly script",
async () => {
const redis = new Redis(client);
const value = randomID();
const key = newKey();
await redis.set(key, value);
const script = redis.createScript("return redis.call('GET', KEYS[1]);", { readonly: true });

const res = await script.evalRo([key], []);
expect(res).toEqual(value);
},
{ timeout: 15_000 }
);

test(
"throws when write commands are used",
async () => {
const redis = new Redis(client);
const value = randomID();
const key = newKey();
await redis.set(key, value);
const script = redis.createScript("return redis.call('DEL', KEYS[1]);", { readonly: true });

expect(async () => {
await script.evalRo([key], []);
}).toThrow();
},
{ timeout: 15_000 }
);
});
Loading
Loading