@o3co/auth-provider-store-redis 0.0.0 → 0.18.0-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +2 -3
- package/package.json +18 -3
- package/redis/README.md +45 -0
- package/redis/config.example +4 -0
- package/redis/src/module.d.ts +2 -0
- package/redis/src/module.js +165 -0
- package/redis/src/probe.d.ts +4 -0
- package/redis/src/probe.js +9 -0
- package/redis/src/redis-store.d.ts +13 -0
- package/redis/src/redis-store.js +240 -0
- package/redis/src/rounds.d.ts +5 -0
- package/redis/src/rounds.js +25 -0
- package/redis/src/scripts.d.ts +26 -0
- package/redis/src/scripts.js +241 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 1o1 Co. Ltd.
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
# @o3co/auth-provider-store-redis
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
publisher. It has no contents. Use 0.18.0-rc.1 or later.
|
|
3
|
+
Part of auth-provider 0.18.0-rc.1, built from `modules/store-redis` of https://github.com/o3co/auth.provider. Its modules, settings and documentation are there.
|
|
5
4
|
|
|
6
|
-
|
|
5
|
+
Copyright 2026 1o1 Co. Ltd. Licensed under the Apache License, Version 2.0.
|
package/package.json
CHANGED
|
@@ -1,10 +1,25 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@o3co/auth-provider-store-redis",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.18.0-rc.1",
|
|
4
|
+
"type": "module",
|
|
4
5
|
"license": "Apache-2.0",
|
|
5
6
|
"repository": {
|
|
6
7
|
"type": "git",
|
|
7
|
-
"url": "
|
|
8
|
+
"url": "https://github.com/o3co/auth.provider",
|
|
8
9
|
"directory": "modules/store-redis"
|
|
10
|
+
},
|
|
11
|
+
"engines": {
|
|
12
|
+
"node": ">=24"
|
|
13
|
+
},
|
|
14
|
+
"exports": {
|
|
15
|
+
"./redis/module": {
|
|
16
|
+
"types": "./redis/src/module.d.ts",
|
|
17
|
+
"default": "./redis/src/module.js"
|
|
18
|
+
}
|
|
19
|
+
},
|
|
20
|
+
"dependencies": {
|
|
21
|
+
"@o3co/auth-provider-foundation": "0.18.0-rc.1",
|
|
22
|
+
"ioredis": "5.11.1",
|
|
23
|
+
"zod": "4.6.5"
|
|
9
24
|
}
|
|
10
|
-
}
|
|
25
|
+
}
|
package/redis/README.md
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
# redis
|
|
2
|
+
|
|
3
|
+
## Responsibilities
|
|
4
|
+
- Implements the `store` contract with Redis, with one script per shape of basic operation and none per feature.
|
|
5
|
+
- Maps each partition to a hash tag, so a batch and a consistent read run in one slot.
|
|
6
|
+
- Checks, once at boot, that the Redis configuration gives the declared spaces their guarantees.
|
|
7
|
+
- Confirms an answer before giving it, for spaces that need replicated or confirmed reads.
|
|
8
|
+
|
|
9
|
+
## Not here
|
|
10
|
+
- Space names and meanings, and the shapes of values. Which feature uses it.
|
|
11
|
+
|
|
12
|
+
## Offers
|
|
13
|
+
- Composition definition only: the `store` contract's implementation.
|
|
14
|
+
- The probe `redis` at `kernel`'s `probes`, which PINGs both connections.
|
|
15
|
+
- Operator section:
|
|
16
|
+
- `url` (`redis` or `rediss`), `prefix` (lower-case letters, digits and `-`; default `store`).
|
|
17
|
+
- `connect-timeout-ms` (default 2000), `command-timeout-ms` (default 1000), `replication-timeout-ms` (default 1000).
|
|
18
|
+
- `replication`: `replicas` or `none`, required when a space needs replicated or confirmed reads.
|
|
19
|
+
|
|
20
|
+
## Invariants
|
|
21
|
+
- Boot is refused on Redis below 7.0, a server that is no primary, or a cluster, proxies splitting keys across nodes included.
|
|
22
|
+
- Boot is refused on a no eviction space without `noeviction`, and on a durable space without `appendonly yes` and `appendfsync always`.
|
|
23
|
+
- Boot is refused on a space needing replicated or confirmed reads without `replication`.
|
|
24
|
+
- A refusal or a warning never tells the URL, which may hold a password; an error event is logged by its name alone.
|
|
25
|
+
- `replicas`: at boot, `min-replicas-to-write` and `min-replicas-max-lag` are 1 or more; at runtime, no replica seen is unavailable.
|
|
26
|
+
- `none`: the operator states there is no failover, so even confirmed writes are lost by one; a replica seen, at boot or at runtime, is refused or unavailable.
|
|
27
|
+
- A confirmation writes the confirmation key on a connection of its own, then waits until every replica ROLE shows has it.
|
|
28
|
+
- A timeout, too few replicas, or another server than the one that answered is unavailable, the answer then unknown.
|
|
29
|
+
- A confirmation asked during a round rides on the next round.
|
|
30
|
+
- Every script first deletes keys and set members whose expiry is at or before its time, as Redis still holds them then.
|
|
31
|
+
- Versions are `server.epoch.n` and never repeat after a restart, a failover, or the end of the key counting them.
|
|
32
|
+
- A command whose reply was lost is never sent again; a dropped connection fails at once, and nothing ends the process.
|
|
33
|
+
- The store clock is Redis's time; values, counts and sets are kept in separate keys, values untouched.
|
|
34
|
+
- Outside the guarantees, the operator's: keeping a detached or lagging replica from promotion, replicas' disk writes, `CONFIG SET` after boot.
|
|
35
|
+
|
|
36
|
+
## Data
|
|
37
|
+
- Keys under the prefix, one hash tag per space and partition, holding values, counts, sets, versions and marks.
|
|
38
|
+
|
|
39
|
+
## Depends on
|
|
40
|
+
- `kernel`, `store`
|
|
41
|
+
|
|
42
|
+
## Vocabulary
|
|
43
|
+
- slot: the range of keys one node holds; a partition fits in one.
|
|
44
|
+
- confirmation key: one key per prefix, written in a confirmation round, apart from idempotency marks.
|
|
45
|
+
- round: one write to the confirmation key and one WAIT.
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import { contract, defineModule, probes } from "@o3co/auth-provider-foundation/kernel";
|
|
2
|
+
import { spaces, store } from "@o3co/auth-provider-foundation/store";
|
|
3
|
+
import { Redis } from "ioredis";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
import { redisProbe } from "./probe.js";
|
|
6
|
+
import { redisStore } from "./redis-store.js";
|
|
7
|
+
const section = z.strictObject({
|
|
8
|
+
url: z.url({ protocol: /^rediss?$/ }).describe("The Redis server to connect to."),
|
|
9
|
+
prefix: z
|
|
10
|
+
.string()
|
|
11
|
+
.regex(/^[a-z0-9-]+$/)
|
|
12
|
+
.default("store")
|
|
13
|
+
.describe("What every key the store writes begins with."),
|
|
14
|
+
"connect-timeout-ms": z
|
|
15
|
+
.number()
|
|
16
|
+
.int()
|
|
17
|
+
.min(100)
|
|
18
|
+
.default(2000)
|
|
19
|
+
.describe("How long connecting to Redis may take, in milliseconds."),
|
|
20
|
+
"replication-timeout-ms": z
|
|
21
|
+
.number()
|
|
22
|
+
.int()
|
|
23
|
+
.min(1)
|
|
24
|
+
.max(60_000)
|
|
25
|
+
.default(1000)
|
|
26
|
+
.describe("How long a confirmation waits for every replica to have a write, in milliseconds."),
|
|
27
|
+
"command-timeout-ms": z
|
|
28
|
+
.number()
|
|
29
|
+
.int()
|
|
30
|
+
.min(10)
|
|
31
|
+
.max(60_000)
|
|
32
|
+
.default(1000)
|
|
33
|
+
.describe("How long one Redis command may take, in milliseconds."),
|
|
34
|
+
replication: z
|
|
35
|
+
.enum(["none", "replicas"])
|
|
36
|
+
.optional()
|
|
37
|
+
.describe('Required when a space asks for replication or confirmed reads. "replicas": every write must reach the replicas, and Redis itself must refuse writes without them. "none": the operator states there is no failover at all, accepting that a failover would lose writes.'),
|
|
38
|
+
});
|
|
39
|
+
const minimumVersion = [7, 0];
|
|
40
|
+
async function configValue(client, name) {
|
|
41
|
+
const pair = (await client.config("GET", name));
|
|
42
|
+
return pair[1];
|
|
43
|
+
}
|
|
44
|
+
const roleOf = async (client) => (await client.call("ROLE"));
|
|
45
|
+
const replicasOf = (role) => (Array.isArray(role[2]) ? role[2].length : 0);
|
|
46
|
+
async function serverProblems(client, role) {
|
|
47
|
+
const problems = [];
|
|
48
|
+
if (role[0] !== "master")
|
|
49
|
+
problems.push("connect to a primary (role master)");
|
|
50
|
+
if (/cluster_enabled:1/.test(await client.info("cluster"))) {
|
|
51
|
+
problems.push("Redis cluster, and proxies that split keys across nodes, are not supported");
|
|
52
|
+
}
|
|
53
|
+
const version = /redis_version:(\d+)\.(\d+)/.exec(await client.info("server"));
|
|
54
|
+
const [major, minor] = [Number(version?.[1] ?? 0), Number(version?.[2] ?? 0)];
|
|
55
|
+
if (major < (minimumVersion[0] ?? 0) ||
|
|
56
|
+
(major === minimumVersion[0] && minor < (minimumVersion[1] ?? 0))) {
|
|
57
|
+
problems.push(`needs Redis ${minimumVersion.join(".")} or later`);
|
|
58
|
+
}
|
|
59
|
+
return problems;
|
|
60
|
+
}
|
|
61
|
+
async function evictionProblems(client, declared) {
|
|
62
|
+
const kept = declared.filter((s) => s.guarantees.includes("no-eviction"));
|
|
63
|
+
if (kept.length === 0 || (await configValue(client, "maxmemory-policy")) === "noeviction")
|
|
64
|
+
return [];
|
|
65
|
+
const names = kept.map((s) => s.name).join(", ");
|
|
66
|
+
return [`the no eviction guarantee needs maxmemory-policy noeviction: ${names}`];
|
|
67
|
+
}
|
|
68
|
+
async function replicationProblems(client, role, declared, replication) {
|
|
69
|
+
const replicated = declared.filter((s) => s.guarantees.includes("replicated") || s.guarantees.includes("confirmed-reads"));
|
|
70
|
+
if (replicated.length === 0)
|
|
71
|
+
return [];
|
|
72
|
+
if (replication === undefined) {
|
|
73
|
+
const names = replicated.map((s) => s.name).join(", ");
|
|
74
|
+
return [
|
|
75
|
+
`spaces need replicated or confirmed reads, so redis.replication (none or replicas) is required: ${names}`,
|
|
76
|
+
];
|
|
77
|
+
}
|
|
78
|
+
if (replication === "replicas" &&
|
|
79
|
+
(Number(await configValue(client, "min-replicas-to-write")) < 1 ||
|
|
80
|
+
Number(await configValue(client, "min-replicas-max-lag")) < 1)) {
|
|
81
|
+
return [
|
|
82
|
+
"with replication replicas, set min-replicas-to-write and min-replicas-max-lag to 1 or more",
|
|
83
|
+
];
|
|
84
|
+
}
|
|
85
|
+
if (replication === "none" && replicasOf(role) > 0) {
|
|
86
|
+
return ["replication is none but a replica is connected"];
|
|
87
|
+
}
|
|
88
|
+
return [];
|
|
89
|
+
}
|
|
90
|
+
async function durabilityProblems(client, declared) {
|
|
91
|
+
const durable = declared.filter((s) => s.guarantees.includes("durable"));
|
|
92
|
+
if (durable.length === 0)
|
|
93
|
+
return [];
|
|
94
|
+
const persisted = (await configValue(client, "appendonly")) === "yes" &&
|
|
95
|
+
(await configValue(client, "appendfsync")) === "always";
|
|
96
|
+
if (persisted)
|
|
97
|
+
return [];
|
|
98
|
+
const names = durable.map((s) => s.name).join(", ");
|
|
99
|
+
return [`the durable guarantee needs appendonly yes and appendfsync always: ${names}`];
|
|
100
|
+
}
|
|
101
|
+
/** What the server's settings fail to give the declared spaces; empty when everything holds. */
|
|
102
|
+
async function unmet(client, declared, replication) {
|
|
103
|
+
const role = await roleOf(client);
|
|
104
|
+
return [
|
|
105
|
+
...(await serverProblems(client, role)),
|
|
106
|
+
...(await evictionProblems(client, declared)),
|
|
107
|
+
...(await replicationProblems(client, role, declared, replication)),
|
|
108
|
+
...(await durabilityProblems(client, declared)),
|
|
109
|
+
];
|
|
110
|
+
}
|
|
111
|
+
/** The two connections, open and checked, for the store and its probe alike. */
|
|
112
|
+
const connections = contract("redis.connections");
|
|
113
|
+
export default defineModule({ name: "redis", section }, (m) => [
|
|
114
|
+
m.provide(connections).by(async (c) => {
|
|
115
|
+
const client = new Redis(c.section.url, {
|
|
116
|
+
lazyConnect: true,
|
|
117
|
+
connectTimeout: c.section["connect-timeout-ms"],
|
|
118
|
+
maxRetriesPerRequest: 0,
|
|
119
|
+
enableOfflineQueue: false,
|
|
120
|
+
// A command whose reply was lost must not be sent again on a new connection: a resent
|
|
121
|
+
// WAIT would confirm nothing, and a resent script would run twice.
|
|
122
|
+
autoResendUnfulfilledCommands: false,
|
|
123
|
+
commandTimeout: c.section["command-timeout-ms"],
|
|
124
|
+
});
|
|
125
|
+
client.on("error", () => c.log.warn("redis.error"));
|
|
126
|
+
const confirmer = client.duplicate({
|
|
127
|
+
commandTimeout: c.section["replication-timeout-ms"] + c.section["command-timeout-ms"],
|
|
128
|
+
});
|
|
129
|
+
confirmer.on("error", () => c.log.warn("redis.error"));
|
|
130
|
+
let problems;
|
|
131
|
+
const declared = await c.collect(spaces);
|
|
132
|
+
try {
|
|
133
|
+
await client.connect();
|
|
134
|
+
await confirmer.connect();
|
|
135
|
+
problems = await unmet(client, declared, c.section.replication);
|
|
136
|
+
}
|
|
137
|
+
catch {
|
|
138
|
+
client.disconnect();
|
|
139
|
+
confirmer.disconnect();
|
|
140
|
+
return c.refuse("redis.url", "cannot connect to Redis, or cannot check its configuration");
|
|
141
|
+
}
|
|
142
|
+
if (problems.length > 0) {
|
|
143
|
+
client.disconnect();
|
|
144
|
+
confirmer.disconnect();
|
|
145
|
+
return c.refuse("redis", problems.join("; "));
|
|
146
|
+
}
|
|
147
|
+
c.onStop(async () => {
|
|
148
|
+
await client.quit().catch(() => client.disconnect());
|
|
149
|
+
await confirmer.quit().catch(() => confirmer.disconnect());
|
|
150
|
+
});
|
|
151
|
+
return { client, confirmer, declared };
|
|
152
|
+
}),
|
|
153
|
+
m.provide(store).by(async (c) => {
|
|
154
|
+
const { client, confirmer, declared } = await c.get(connections);
|
|
155
|
+
return redisStore(client, confirmer, {
|
|
156
|
+
prefix: c.section.prefix,
|
|
157
|
+
replicationTimeoutMs: c.section["replication-timeout-ms"],
|
|
158
|
+
replication: c.section.replication,
|
|
159
|
+
}, declared);
|
|
160
|
+
}),
|
|
161
|
+
m.contribute(probes).by(async (c) => {
|
|
162
|
+
const { client, confirmer } = await c.get(connections);
|
|
163
|
+
return redisProbe([client, confirmer]);
|
|
164
|
+
}),
|
|
165
|
+
]);
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { Probe } from "@o3co/auth-provider-foundation/kernel";
|
|
2
|
+
import type { Redis } from "ioredis";
|
|
3
|
+
/** Passes when every connection answers PING; a dropped one fails at once, having no offline queue. */
|
|
4
|
+
export declare function redisProbe(connections: readonly Redis[]): Probe;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** Passes when every connection answers PING; a dropped one fails at once, having no offline queue. */
|
|
2
|
+
export function redisProbe(connections) {
|
|
3
|
+
return {
|
|
4
|
+
name: "redis",
|
|
5
|
+
check: async () => {
|
|
6
|
+
await Promise.all(connections.map((connection) => connection.ping()));
|
|
7
|
+
},
|
|
8
|
+
};
|
|
9
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { type Space, type Store } from "@o3co/auth-provider-foundation/store";
|
|
2
|
+
import type { Redis } from "ioredis";
|
|
3
|
+
export interface RedisStoreOptions {
|
|
4
|
+
readonly prefix: string;
|
|
5
|
+
readonly replicationTimeoutMs: number;
|
|
6
|
+
/** What the operator declared: no failover at all, or replicas that must take every write. */
|
|
7
|
+
readonly replication: "none" | "replicas" | undefined;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* `client` serves the operations; `confirmer` is a connection of its own for confirming
|
|
11
|
+
* replication, so a WAIT never holds up the other commands.
|
|
12
|
+
*/
|
|
13
|
+
export declare function redisStore(client: Redis, confirmer: Redis, options: RedisStoreOptions, declared: readonly Space[]): Store;
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { Unavailable } from "@o3co/auth-provider-foundation/kernel";
|
|
3
|
+
import { canonicalJson, checkedStore, codePointOrder, idempotencyRequest, } from "@o3co/auth-provider-foundation/store";
|
|
4
|
+
import { sharedRounds } from "./rounds.js";
|
|
5
|
+
import * as scripts from "./scripts.js";
|
|
6
|
+
const enc = encodeURIComponent;
|
|
7
|
+
/** cjson turns empty or sparse Lua arrays into objects; rebuild them by count. */
|
|
8
|
+
function list(value, n) {
|
|
9
|
+
return Array.from({ length: n }, (_, i) => value[i]);
|
|
10
|
+
}
|
|
11
|
+
/** Script answers carry numbers as strings; turn the known ones back into numbers (the fields scripts.ts answers). */
|
|
12
|
+
function numbers(answer) {
|
|
13
|
+
const out = { ...answer };
|
|
14
|
+
for (const field of ["now", "remainingMs", "resetAt", "count"]) {
|
|
15
|
+
if (typeof out[field] === "string")
|
|
16
|
+
out[field] = Number(out[field]);
|
|
17
|
+
}
|
|
18
|
+
return out;
|
|
19
|
+
}
|
|
20
|
+
const digest = (request) => createHash("sha256").update(request).digest("hex");
|
|
21
|
+
/** Where a script answer records the server it ran on, out of sight of the callers. */
|
|
22
|
+
const servedBy = Symbol("served by");
|
|
23
|
+
const writtenKinds = new Set(["written", "removed", "taken", "committed", "counted"]);
|
|
24
|
+
/**
|
|
25
|
+
* `client` serves the operations; `confirmer` is a connection of its own for confirming
|
|
26
|
+
* replication, so a WAIT never holds up the other commands.
|
|
27
|
+
*/
|
|
28
|
+
export function redisStore(client, confirmer, options, declared) {
|
|
29
|
+
const { prefix, replicationTimeoutMs } = options;
|
|
30
|
+
const slot = (key) => `${prefix}:{${enc(key.space.name)}:${enc(key.partition)}}`;
|
|
31
|
+
const valueKey = (key) => `${slot(key)}:v:${enc(key.name)}`;
|
|
32
|
+
const counterKey = (key) => `${slot(key)}:c:${enc(key.name)}`;
|
|
33
|
+
const setKey = (key) => `${slot(key)}:s:${enc(key.name)}`;
|
|
34
|
+
const versionKey = (key) => `${slot(key)}:#version`;
|
|
35
|
+
const markKey = (key, mark) => `${slot(key)}:#mark:${enc(mark ?? "")}`;
|
|
36
|
+
/** Runs a script; every answer comes with the run id of the server that computed it. */
|
|
37
|
+
const run = async (script, keys, args) => {
|
|
38
|
+
let reply;
|
|
39
|
+
try {
|
|
40
|
+
reply = await client.eval(script, keys.length, ...keys, ...args);
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
throw new Unavailable("store");
|
|
44
|
+
}
|
|
45
|
+
const text = String(reply);
|
|
46
|
+
const split = text.indexOf("\n");
|
|
47
|
+
const answer = numbers(JSON.parse(text.slice(split + 1)));
|
|
48
|
+
Object.defineProperty(answer, servedBy, { value: text.slice(0, split), enumerable: false });
|
|
49
|
+
return answer;
|
|
50
|
+
};
|
|
51
|
+
/**
|
|
52
|
+
* One confirmation round: in one trip, learn the replicas and the server, and write a key on
|
|
53
|
+
* the confirming connection; then wait until every replica online now has it. Replication is
|
|
54
|
+
* ordered, so a round covers everything the primary did before. WAIT waits only for its own
|
|
55
|
+
* connection's writes, hence the key; and a connection of its own keeps WAIT from holding other
|
|
56
|
+
* commands. The confirming connection must talk to the same server as the operations (a DNS or
|
|
57
|
+
* load-balancer change can part them), and the replicas must match what the operator declared.
|
|
58
|
+
*/
|
|
59
|
+
const round = async () => {
|
|
60
|
+
try {
|
|
61
|
+
const replies = await confirmer
|
|
62
|
+
.pipeline()
|
|
63
|
+
.call("ROLE")
|
|
64
|
+
.info("server")
|
|
65
|
+
.set(`${prefix}:#confirm`, "1", "PX", 60_000)
|
|
66
|
+
.exec();
|
|
67
|
+
if (!replies || replies.some(([error]) => error))
|
|
68
|
+
throw new Error("confirmation failed");
|
|
69
|
+
const role = replies[0]?.[1];
|
|
70
|
+
const server = /run_id:(\w+)/.exec(String(replies[1]?.[1]))?.[1];
|
|
71
|
+
if (role[0] !== "master" || server === undefined)
|
|
72
|
+
throw new Error("not a primary");
|
|
73
|
+
const replicas = Array.isArray(role[2]) ? role[2].length : 0;
|
|
74
|
+
if (options.replication === "none") {
|
|
75
|
+
if (replicas === 0)
|
|
76
|
+
return server;
|
|
77
|
+
throw new Error("replicas seen where none were declared");
|
|
78
|
+
}
|
|
79
|
+
// A primary cut off from the others also sees none, and what it confirmed would be lost.
|
|
80
|
+
if (replicas === 0)
|
|
81
|
+
throw new Error("no replica to confirm with");
|
|
82
|
+
const acknowledged = Number(await confirmer.call("WAIT", replicas, replicationTimeoutMs));
|
|
83
|
+
if (acknowledged >= replicas)
|
|
84
|
+
return server;
|
|
85
|
+
}
|
|
86
|
+
catch { }
|
|
87
|
+
throw new Unavailable("store");
|
|
88
|
+
};
|
|
89
|
+
const confirmed = sharedRounds(round);
|
|
90
|
+
/**
|
|
91
|
+
* Replicated spaces confirm what they wrote; spaces asking for confirmed reads confirm every
|
|
92
|
+
* answer. The round must have run on the server that computed the answer.
|
|
93
|
+
*/
|
|
94
|
+
const confirmOn = async (key, wrote, answer) => {
|
|
95
|
+
const guarantees = key.space.guarantees;
|
|
96
|
+
const needed = guarantees.includes("confirmed-reads") || (guarantees.includes("replicated") && wrote);
|
|
97
|
+
if (!needed)
|
|
98
|
+
return;
|
|
99
|
+
const server = await confirmed();
|
|
100
|
+
if (server !== answer[servedBy])
|
|
101
|
+
throw new Unavailable("store");
|
|
102
|
+
};
|
|
103
|
+
const confirm = async (key, answer) => {
|
|
104
|
+
await confirmOn(key, writtenKinds.has(answer.kind), answer);
|
|
105
|
+
return answer;
|
|
106
|
+
};
|
|
107
|
+
const expiryArgs = (expiry) => {
|
|
108
|
+
if (expiry.kind === "after" || expiry.kind === "extend")
|
|
109
|
+
return [expiry.kind, String(expiry.ms)];
|
|
110
|
+
if (expiry.kind === "at")
|
|
111
|
+
return ["at", String(expiry.at)];
|
|
112
|
+
return [expiry.kind, ""];
|
|
113
|
+
};
|
|
114
|
+
const entry = (raw) => raw
|
|
115
|
+
? Object.freeze({
|
|
116
|
+
value: JSON.parse(raw.value),
|
|
117
|
+
version: raw.version,
|
|
118
|
+
expiresAt: raw.expiresAt === null ? null : Number(raw.expiresAt),
|
|
119
|
+
})
|
|
120
|
+
: null;
|
|
121
|
+
const samePartition = (keys) => {
|
|
122
|
+
if (new Set(keys.map(slot)).size > 1)
|
|
123
|
+
throw new Error("keys span more than one partition");
|
|
124
|
+
};
|
|
125
|
+
const marked = (options) => options?.idempotency ? "1" : "0";
|
|
126
|
+
const writeWith = async (mode, key, value, expected, options) => {
|
|
127
|
+
const [kind, arg] = expiryArgs(options.expiry);
|
|
128
|
+
const args = mode === "replaceIf" ? [expected, value, options.expiry] : [value, options.expiry];
|
|
129
|
+
const answer = await run(scripts.write, [valueKey(key), versionKey(key), markKey(key, options.idempotency)], [
|
|
130
|
+
mode,
|
|
131
|
+
canonicalJson(value),
|
|
132
|
+
expected,
|
|
133
|
+
kind,
|
|
134
|
+
arg,
|
|
135
|
+
options.deadline ?? "",
|
|
136
|
+
digest(idempotencyRequest(mode, [key], args)),
|
|
137
|
+
marked(options),
|
|
138
|
+
]);
|
|
139
|
+
return confirm(key, answer);
|
|
140
|
+
};
|
|
141
|
+
return checkedStore({
|
|
142
|
+
get: async (key) => {
|
|
143
|
+
const read = await confirm(key, await run(scripts.read, [valueKey(key)], []));
|
|
144
|
+
return { entry: entry(list(read.entries, 1)[0]), now: read.now };
|
|
145
|
+
},
|
|
146
|
+
getMany: async (keys) => {
|
|
147
|
+
samePartition(keys);
|
|
148
|
+
const read = await run(scripts.read, keys.map(valueKey), []);
|
|
149
|
+
const [first] = keys;
|
|
150
|
+
if (first)
|
|
151
|
+
await confirm(first, read);
|
|
152
|
+
return { entries: list(read.entries, read.n).map(entry), now: read.now };
|
|
153
|
+
},
|
|
154
|
+
put: (key, value, options) => writeWith("put", key, value, "", options),
|
|
155
|
+
putIfAbsent: (key, value, options) => writeWith("putIfAbsent", key, value, "", options),
|
|
156
|
+
replaceIf: (key, version, value, options) => writeWith("replaceIf", key, value, version, options),
|
|
157
|
+
removeIf: async (key, expected, options) => {
|
|
158
|
+
const by = "version" in expected ? "version" : "value";
|
|
159
|
+
const target = "version" in expected ? expected.version : canonicalJson(expected.value);
|
|
160
|
+
const answer = await run(scripts.removeIf, [valueKey(key), markKey(key, options?.idempotency)], [
|
|
161
|
+
by,
|
|
162
|
+
target,
|
|
163
|
+
options?.deadline ?? "",
|
|
164
|
+
digest(idempotencyRequest("removeIf", [key], [expected])),
|
|
165
|
+
marked(options),
|
|
166
|
+
]);
|
|
167
|
+
await confirm(key, answer);
|
|
168
|
+
return answer.kind === "removed"
|
|
169
|
+
? { kind: "removed", old: entry(answer.old) }
|
|
170
|
+
: answer;
|
|
171
|
+
},
|
|
172
|
+
take: async (key, options) => {
|
|
173
|
+
const answer = await run(scripts.take, [valueKey(key), markKey(key, options?.idempotency)], [options?.deadline ?? "", digest(idempotencyRequest("take", [key], [])), marked(options)]);
|
|
174
|
+
await confirm(key, answer);
|
|
175
|
+
return answer.kind === "taken"
|
|
176
|
+
? { kind: "taken", entry: entry(answer.entry) }
|
|
177
|
+
: answer;
|
|
178
|
+
},
|
|
179
|
+
batch: async (conditions, writes, options) => {
|
|
180
|
+
const keys = [...conditions.map((c) => c.key), ...writes.map((w) => w.key)];
|
|
181
|
+
samePartition(keys);
|
|
182
|
+
const [first] = keys;
|
|
183
|
+
if (!first)
|
|
184
|
+
return run(scripts.deadlineOnly, [], [options?.deadline ?? ""]);
|
|
185
|
+
const names = [...new Set(keys.map(valueKey))];
|
|
186
|
+
const index = (key) => names.indexOf(valueKey(key)) + 1;
|
|
187
|
+
const spec = {
|
|
188
|
+
conditions: conditions.map((c) => "absent" in c
|
|
189
|
+
? { i: index(c.key), absent: true }
|
|
190
|
+
: { i: index(c.key), version: c.version }),
|
|
191
|
+
writes: writes.map((w) => {
|
|
192
|
+
if ("remove" in w)
|
|
193
|
+
return { i: index(w.key), remove: true };
|
|
194
|
+
const [kind, arg] = expiryArgs(w.expiry);
|
|
195
|
+
return { i: index(w.key), put: canonicalJson(w.put), kind, arg };
|
|
196
|
+
}),
|
|
197
|
+
};
|
|
198
|
+
const request = idempotencyRequest("batch", keys, [
|
|
199
|
+
conditions.map((c) => ("absent" in c ? { absent: true } : { version: c.version })),
|
|
200
|
+
writes.map((w) => ("remove" in w ? null : [w.put, w.expiry])),
|
|
201
|
+
]);
|
|
202
|
+
const answer = await run(scripts.batch, [...names, versionKey(first), markKey(first, options?.idempotency)], [JSON.stringify(spec), options?.deadline ?? "", digest(request), marked(options)]);
|
|
203
|
+
await confirm(first, answer);
|
|
204
|
+
return answer.kind === "committed"
|
|
205
|
+
? { kind: "committed", versions: list(answer.versions, answer.n) }
|
|
206
|
+
: answer;
|
|
207
|
+
},
|
|
208
|
+
count: async (key, window, options) => {
|
|
209
|
+
const answer = await run(scripts.count, [counterKey(key), markKey(key, options?.idempotency)], [
|
|
210
|
+
window.ms,
|
|
211
|
+
window.limit,
|
|
212
|
+
options?.deadline ?? "",
|
|
213
|
+
digest(idempotencyRequest("count", [key], [window.ms, window.limit])),
|
|
214
|
+
marked(options),
|
|
215
|
+
]);
|
|
216
|
+
return confirm(key, answer);
|
|
217
|
+
},
|
|
218
|
+
setAdd: async (key, member, score, options) => {
|
|
219
|
+
const [kind, arg] = expiryArgs(options.expiry);
|
|
220
|
+
const answer = await run(scripts.setAdd, [setKey(key)], [member, score, options.cap, kind, arg]);
|
|
221
|
+
// A set's add always writes.
|
|
222
|
+
await confirmOn(key, true, answer);
|
|
223
|
+
return { evicted: list(answer.evicted, answer.n) };
|
|
224
|
+
},
|
|
225
|
+
setMembers: async (key) => {
|
|
226
|
+
const answer = await confirm(key, await run(scripts.setMembers, [setKey(key)], []));
|
|
227
|
+
const flat = Array.isArray(answer.members) ? answer.members : [];
|
|
228
|
+
const members = [];
|
|
229
|
+
for (let i = 0; i < flat.length; i += 2) {
|
|
230
|
+
members.push({ member: flat[i], score: Number(flat[i + 1]) });
|
|
231
|
+
}
|
|
232
|
+
members.sort((a, b) => codePointOrder(a.member, b.member));
|
|
233
|
+
return { members, now: answer.now };
|
|
234
|
+
},
|
|
235
|
+
setRemove: async (key, member) => {
|
|
236
|
+
await confirm(key, await run(scripts.setRemove, [setKey(key)], [member]));
|
|
237
|
+
},
|
|
238
|
+
now: async () => (await run(scripts.now, [], [])).now,
|
|
239
|
+
}, declared);
|
|
240
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shares confirmation rounds: a call made while a round is running waits for the next round,
|
|
3
|
+
* never the running one, whose start may predate the caller's own work.
|
|
4
|
+
*/
|
|
5
|
+
export function sharedRounds(round) {
|
|
6
|
+
let running;
|
|
7
|
+
let next;
|
|
8
|
+
const start = () => {
|
|
9
|
+
running = round().finally(() => {
|
|
10
|
+
running = undefined;
|
|
11
|
+
});
|
|
12
|
+
return running;
|
|
13
|
+
};
|
|
14
|
+
return () => {
|
|
15
|
+
if (!running)
|
|
16
|
+
return start();
|
|
17
|
+
next ??= running
|
|
18
|
+
.catch(() => { })
|
|
19
|
+
.then(() => {
|
|
20
|
+
next = undefined;
|
|
21
|
+
return start();
|
|
22
|
+
});
|
|
23
|
+
return next;
|
|
24
|
+
};
|
|
25
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/** KEYS: key, version key, mark key. ARGV: mode, value, expected, kind, arg, deadline, digest, has mark. */
|
|
2
|
+
export declare const write = "\nlocal t = redis.call('TIME')\nlocal now = tonumber(t[1]) * 1000 + math.floor(tonumber(t[2]) / 1000)\nlocal function num(x) return string.format('%.0f', x) end\nlocal run_id = string.match(redis.call('INFO', 'server'), 'run_id:(%w+)')\n-- Every answer names the server it was computed on, so a confirmation is checked against it.\nlocal function out(answer) return run_id .. '\\n' .. answer end\n-- An entry is gone at its very expiry time by this script's clock; Redis would still hold it.\nfor _, key in ipairs(KEYS) do\n local expires = redis.call('PEXPIRETIME', key)\n if expires >= 0 and expires <= now then redis.call('DEL', key) end\nend\nlocal function next_version(vkey)\n local server = string.sub(run_id, 1, 12)\n .. string.sub(string.match(redis.call('INFO', 'replication'), 'master_replid:(%w+)'), 1, 12)\n local epoch = redis.call('HGET', vkey, 'epoch')\n if not epoch then\n epoch = t[1] .. string.format('%06d', tonumber(t[2]))\n redis.call('HSET', vkey, 'epoch', epoch)\n end\n local n = redis.call('HINCRBY', vkey, 'n', 1)\n redis.call('PEXPIRE', vkey, 86400000)\n return server .. '.' .. epoch .. '.' .. num(n)\nend\nlocal function expiry(kind, arg, current)\n if kind == 'after' then return now + tonumber(arg) end\n if kind == 'at' then return tonumber(arg) end\n if kind == 'never' then return nil end\n if kind == 'keep' then\n if current < 0 then return nil end\n return current\n end\n -- extend: never shorter than it was, and a key that never ends stays so.\n if current == -1 then return nil end\n return math.max(current, now + tonumber(arg))\nend\nlocal function store_value(key, vkey, value, expires)\n local v = next_version(vkey)\n redis.call('DEL', key)\n redis.call('HSET', key, 'v', value, 'ver', v)\n if expires ~= nil then redis.call('PEXPIREAT', key, expires) end\n return v\nend\nlocal function guard(ikey, digest, deadline)\n if ikey ~= '' then\n local seen = redis.call('GET', ikey)\n if seen then\n local record = cjson.decode(seen)\n if record.d == digest then return record.a end\n return cjson.encode({kind = 'reused'})\n end\n end\n if deadline ~= '' and now > tonumber(deadline) then return cjson.encode({kind = 'late'}) end\n return nil\nend\n-- A mark is kept a second past its deadline, or five minutes and a second without one, as store says.\nlocal mark_without_deadline_ms = 300000\nlocal mark_past_deadline_ms = 1000\nlocal function remember(ikey, digest, answer, deadline)\n if ikey ~= '' then\n local base = deadline ~= '' and tonumber(deadline) or now + mark_without_deadline_ms\n redis.call('SET', ikey, cjson.encode({d = digest, a = answer}), 'PXAT', base + mark_past_deadline_ms)\n end\n return answer\nend\nlocal function entry(key)\n local held = redis.call('HMGET', key, 'v', 'ver')\n if not held[1] then return false end\n local expires = redis.call('PEXPIRETIME', key)\n return {value = held[1], version = held[2], expiresAt = expires >= 0 and num(expires) or cjson.null}\nend\n\nlocal key, vkey, ikey = KEYS[1], KEYS[2], ARGV[8] == '1' and KEYS[3] or ''\nlocal seen = guard(ikey, ARGV[7], ARGV[6])\nif seen then return out(seen) end\nlocal mode = ARGV[1]\nlocal exists = redis.call('EXISTS', key) == 1\nlocal answer\nif mode == 'putIfAbsent' and exists then\n local ttl = redis.call('PTTL', key)\n answer = cjson.encode({kind = 'exists', remainingMs = ttl >= 0 and num(ttl) or cjson.null})\nelseif mode == 'replaceIf' and not exists then\n answer = cjson.encode({kind = 'missing'})\nelseif mode == 'replaceIf' and redis.call('HGET', key, 'ver') ~= ARGV[3] then\n answer = cjson.encode({kind = 'conflict'})\nelse\n local expires = expiry(ARGV[4], ARGV[5], redis.call('PEXPIRETIME', key))\n answer = cjson.encode({kind = 'written', version = store_value(key, vkey, ARGV[2], expires)})\nend\nreturn out(remember(ikey, ARGV[7], answer, ARGV[6]))\n";
|
|
3
|
+
/** KEYS: key, mark key. ARGV: by ('version'|'value'), expected, deadline, digest, has mark. */
|
|
4
|
+
export declare const removeIf = "\nlocal t = redis.call('TIME')\nlocal now = tonumber(t[1]) * 1000 + math.floor(tonumber(t[2]) / 1000)\nlocal function num(x) return string.format('%.0f', x) end\nlocal run_id = string.match(redis.call('INFO', 'server'), 'run_id:(%w+)')\n-- Every answer names the server it was computed on, so a confirmation is checked against it.\nlocal function out(answer) return run_id .. '\\n' .. answer end\n-- An entry is gone at its very expiry time by this script's clock; Redis would still hold it.\nfor _, key in ipairs(KEYS) do\n local expires = redis.call('PEXPIRETIME', key)\n if expires >= 0 and expires <= now then redis.call('DEL', key) end\nend\nlocal function next_version(vkey)\n local server = string.sub(run_id, 1, 12)\n .. string.sub(string.match(redis.call('INFO', 'replication'), 'master_replid:(%w+)'), 1, 12)\n local epoch = redis.call('HGET', vkey, 'epoch')\n if not epoch then\n epoch = t[1] .. string.format('%06d', tonumber(t[2]))\n redis.call('HSET', vkey, 'epoch', epoch)\n end\n local n = redis.call('HINCRBY', vkey, 'n', 1)\n redis.call('PEXPIRE', vkey, 86400000)\n return server .. '.' .. epoch .. '.' .. num(n)\nend\nlocal function expiry(kind, arg, current)\n if kind == 'after' then return now + tonumber(arg) end\n if kind == 'at' then return tonumber(arg) end\n if kind == 'never' then return nil end\n if kind == 'keep' then\n if current < 0 then return nil end\n return current\n end\n -- extend: never shorter than it was, and a key that never ends stays so.\n if current == -1 then return nil end\n return math.max(current, now + tonumber(arg))\nend\nlocal function store_value(key, vkey, value, expires)\n local v = next_version(vkey)\n redis.call('DEL', key)\n redis.call('HSET', key, 'v', value, 'ver', v)\n if expires ~= nil then redis.call('PEXPIREAT', key, expires) end\n return v\nend\nlocal function guard(ikey, digest, deadline)\n if ikey ~= '' then\n local seen = redis.call('GET', ikey)\n if seen then\n local record = cjson.decode(seen)\n if record.d == digest then return record.a end\n return cjson.encode({kind = 'reused'})\n end\n end\n if deadline ~= '' and now > tonumber(deadline) then return cjson.encode({kind = 'late'}) end\n return nil\nend\n-- A mark is kept a second past its deadline, or five minutes and a second without one, as store says.\nlocal mark_without_deadline_ms = 300000\nlocal mark_past_deadline_ms = 1000\nlocal function remember(ikey, digest, answer, deadline)\n if ikey ~= '' then\n local base = deadline ~= '' and tonumber(deadline) or now + mark_without_deadline_ms\n redis.call('SET', ikey, cjson.encode({d = digest, a = answer}), 'PXAT', base + mark_past_deadline_ms)\n end\n return answer\nend\nlocal function entry(key)\n local held = redis.call('HMGET', key, 'v', 'ver')\n if not held[1] then return false end\n local expires = redis.call('PEXPIRETIME', key)\n return {value = held[1], version = held[2], expiresAt = expires >= 0 and num(expires) or cjson.null}\nend\n\nlocal key, ikey = KEYS[1], ARGV[5] == '1' and KEYS[2] or ''\nlocal seen = guard(ikey, ARGV[4], ARGV[3])\nif seen then return out(seen) end\nlocal held = entry(KEYS[1])\nlocal answer\nif not held then\n answer = cjson.encode({kind = 'missing'})\nelseif (ARGV[1] == 'version' and held.version ~= ARGV[2]) or (ARGV[1] == 'value' and held.value ~= ARGV[2]) then\n answer = cjson.encode({kind = 'conflict'})\nelse\n redis.call('DEL', key)\n answer = cjson.encode({kind = 'removed', old = held})\nend\nreturn out(remember(ikey, ARGV[4], answer, ARGV[3]))\n";
|
|
5
|
+
/** KEYS: the keys to read. */
|
|
6
|
+
export declare const read = "\nlocal t = redis.call('TIME')\nlocal now = tonumber(t[1]) * 1000 + math.floor(tonumber(t[2]) / 1000)\nlocal function num(x) return string.format('%.0f', x) end\nlocal run_id = string.match(redis.call('INFO', 'server'), 'run_id:(%w+)')\n-- Every answer names the server it was computed on, so a confirmation is checked against it.\nlocal function out(answer) return run_id .. '\\n' .. answer end\n-- An entry is gone at its very expiry time by this script's clock; Redis would still hold it.\nfor _, key in ipairs(KEYS) do\n local expires = redis.call('PEXPIRETIME', key)\n if expires >= 0 and expires <= now then redis.call('DEL', key) end\nend\nlocal function next_version(vkey)\n local server = string.sub(run_id, 1, 12)\n .. string.sub(string.match(redis.call('INFO', 'replication'), 'master_replid:(%w+)'), 1, 12)\n local epoch = redis.call('HGET', vkey, 'epoch')\n if not epoch then\n epoch = t[1] .. string.format('%06d', tonumber(t[2]))\n redis.call('HSET', vkey, 'epoch', epoch)\n end\n local n = redis.call('HINCRBY', vkey, 'n', 1)\n redis.call('PEXPIRE', vkey, 86400000)\n return server .. '.' .. epoch .. '.' .. num(n)\nend\nlocal function expiry(kind, arg, current)\n if kind == 'after' then return now + tonumber(arg) end\n if kind == 'at' then return tonumber(arg) end\n if kind == 'never' then return nil end\n if kind == 'keep' then\n if current < 0 then return nil end\n return current\n end\n -- extend: never shorter than it was, and a key that never ends stays so.\n if current == -1 then return nil end\n return math.max(current, now + tonumber(arg))\nend\nlocal function store_value(key, vkey, value, expires)\n local v = next_version(vkey)\n redis.call('DEL', key)\n redis.call('HSET', key, 'v', value, 'ver', v)\n if expires ~= nil then redis.call('PEXPIREAT', key, expires) end\n return v\nend\nlocal function guard(ikey, digest, deadline)\n if ikey ~= '' then\n local seen = redis.call('GET', ikey)\n if seen then\n local record = cjson.decode(seen)\n if record.d == digest then return record.a end\n return cjson.encode({kind = 'reused'})\n end\n end\n if deadline ~= '' and now > tonumber(deadline) then return cjson.encode({kind = 'late'}) end\n return nil\nend\n-- A mark is kept a second past its deadline, or five minutes and a second without one, as store says.\nlocal mark_without_deadline_ms = 300000\nlocal mark_past_deadline_ms = 1000\nlocal function remember(ikey, digest, answer, deadline)\n if ikey ~= '' then\n local base = deadline ~= '' and tonumber(deadline) or now + mark_without_deadline_ms\n redis.call('SET', ikey, cjson.encode({d = digest, a = answer}), 'PXAT', base + mark_past_deadline_ms)\n end\n return answer\nend\nlocal function entry(key)\n local held = redis.call('HMGET', key, 'v', 'ver')\n if not held[1] then return false end\n local expires = redis.call('PEXPIRETIME', key)\n return {value = held[1], version = held[2], expiresAt = expires >= 0 and num(expires) or cjson.null}\nend\n\nlocal entries = {}\nfor i, key in ipairs(KEYS) do entries[i] = entry(key) end\nreturn out(cjson.encode({now = num(now), entries = entries, n = #KEYS}))\n";
|
|
7
|
+
/** KEYS: key, mark key. ARGV: deadline, digest, has mark. */
|
|
8
|
+
export declare const take = "\nlocal t = redis.call('TIME')\nlocal now = tonumber(t[1]) * 1000 + math.floor(tonumber(t[2]) / 1000)\nlocal function num(x) return string.format('%.0f', x) end\nlocal run_id = string.match(redis.call('INFO', 'server'), 'run_id:(%w+)')\n-- Every answer names the server it was computed on, so a confirmation is checked against it.\nlocal function out(answer) return run_id .. '\\n' .. answer end\n-- An entry is gone at its very expiry time by this script's clock; Redis would still hold it.\nfor _, key in ipairs(KEYS) do\n local expires = redis.call('PEXPIRETIME', key)\n if expires >= 0 and expires <= now then redis.call('DEL', key) end\nend\nlocal function next_version(vkey)\n local server = string.sub(run_id, 1, 12)\n .. string.sub(string.match(redis.call('INFO', 'replication'), 'master_replid:(%w+)'), 1, 12)\n local epoch = redis.call('HGET', vkey, 'epoch')\n if not epoch then\n epoch = t[1] .. string.format('%06d', tonumber(t[2]))\n redis.call('HSET', vkey, 'epoch', epoch)\n end\n local n = redis.call('HINCRBY', vkey, 'n', 1)\n redis.call('PEXPIRE', vkey, 86400000)\n return server .. '.' .. epoch .. '.' .. num(n)\nend\nlocal function expiry(kind, arg, current)\n if kind == 'after' then return now + tonumber(arg) end\n if kind == 'at' then return tonumber(arg) end\n if kind == 'never' then return nil end\n if kind == 'keep' then\n if current < 0 then return nil end\n return current\n end\n -- extend: never shorter than it was, and a key that never ends stays so.\n if current == -1 then return nil end\n return math.max(current, now + tonumber(arg))\nend\nlocal function store_value(key, vkey, value, expires)\n local v = next_version(vkey)\n redis.call('DEL', key)\n redis.call('HSET', key, 'v', value, 'ver', v)\n if expires ~= nil then redis.call('PEXPIREAT', key, expires) end\n return v\nend\nlocal function guard(ikey, digest, deadline)\n if ikey ~= '' then\n local seen = redis.call('GET', ikey)\n if seen then\n local record = cjson.decode(seen)\n if record.d == digest then return record.a end\n return cjson.encode({kind = 'reused'})\n end\n end\n if deadline ~= '' and now > tonumber(deadline) then return cjson.encode({kind = 'late'}) end\n return nil\nend\n-- A mark is kept a second past its deadline, or five minutes and a second without one, as store says.\nlocal mark_without_deadline_ms = 300000\nlocal mark_past_deadline_ms = 1000\nlocal function remember(ikey, digest, answer, deadline)\n if ikey ~= '' then\n local base = deadline ~= '' and tonumber(deadline) or now + mark_without_deadline_ms\n redis.call('SET', ikey, cjson.encode({d = digest, a = answer}), 'PXAT', base + mark_past_deadline_ms)\n end\n return answer\nend\nlocal function entry(key)\n local held = redis.call('HMGET', key, 'v', 'ver')\n if not held[1] then return false end\n local expires = redis.call('PEXPIRETIME', key)\n return {value = held[1], version = held[2], expiresAt = expires >= 0 and num(expires) or cjson.null}\nend\n\nlocal ikey = ARGV[3] == '1' and KEYS[2] or ''\nlocal seen = guard(ikey, ARGV[2], ARGV[1])\nif seen then return out(seen) end\nlocal held = entry(KEYS[1])\nlocal answer\nif not held then\n answer = cjson.encode({kind = 'missing'})\nelse\n redis.call('DEL', KEYS[1])\n answer = cjson.encode({kind = 'taken', entry = held})\nend\nreturn out(remember(ikey, ARGV[2], answer, ARGV[1]))\n";
|
|
9
|
+
/**
|
|
10
|
+
* KEYS: the batch keys, then the version key, then the mark key.
|
|
11
|
+
* ARGV: spec JSON {conditions = [{i, version|absent}], writes = [{i, put, kind, arg}|{i, remove}]},
|
|
12
|
+
* deadline, digest, has mark.
|
|
13
|
+
*/
|
|
14
|
+
export declare const batch = "\nlocal t = redis.call('TIME')\nlocal now = tonumber(t[1]) * 1000 + math.floor(tonumber(t[2]) / 1000)\nlocal function num(x) return string.format('%.0f', x) end\nlocal run_id = string.match(redis.call('INFO', 'server'), 'run_id:(%w+)')\n-- Every answer names the server it was computed on, so a confirmation is checked against it.\nlocal function out(answer) return run_id .. '\\n' .. answer end\n-- An entry is gone at its very expiry time by this script's clock; Redis would still hold it.\nfor _, key in ipairs(KEYS) do\n local expires = redis.call('PEXPIRETIME', key)\n if expires >= 0 and expires <= now then redis.call('DEL', key) end\nend\nlocal function next_version(vkey)\n local server = string.sub(run_id, 1, 12)\n .. string.sub(string.match(redis.call('INFO', 'replication'), 'master_replid:(%w+)'), 1, 12)\n local epoch = redis.call('HGET', vkey, 'epoch')\n if not epoch then\n epoch = t[1] .. string.format('%06d', tonumber(t[2]))\n redis.call('HSET', vkey, 'epoch', epoch)\n end\n local n = redis.call('HINCRBY', vkey, 'n', 1)\n redis.call('PEXPIRE', vkey, 86400000)\n return server .. '.' .. epoch .. '.' .. num(n)\nend\nlocal function expiry(kind, arg, current)\n if kind == 'after' then return now + tonumber(arg) end\n if kind == 'at' then return tonumber(arg) end\n if kind == 'never' then return nil end\n if kind == 'keep' then\n if current < 0 then return nil end\n return current\n end\n -- extend: never shorter than it was, and a key that never ends stays so.\n if current == -1 then return nil end\n return math.max(current, now + tonumber(arg))\nend\nlocal function store_value(key, vkey, value, expires)\n local v = next_version(vkey)\n redis.call('DEL', key)\n redis.call('HSET', key, 'v', value, 'ver', v)\n if expires ~= nil then redis.call('PEXPIREAT', key, expires) end\n return v\nend\nlocal function guard(ikey, digest, deadline)\n if ikey ~= '' then\n local seen = redis.call('GET', ikey)\n if seen then\n local record = cjson.decode(seen)\n if record.d == digest then return record.a end\n return cjson.encode({kind = 'reused'})\n end\n end\n if deadline ~= '' and now > tonumber(deadline) then return cjson.encode({kind = 'late'}) end\n return nil\nend\n-- A mark is kept a second past its deadline, or five minutes and a second without one, as store says.\nlocal mark_without_deadline_ms = 300000\nlocal mark_past_deadline_ms = 1000\nlocal function remember(ikey, digest, answer, deadline)\n if ikey ~= '' then\n local base = deadline ~= '' and tonumber(deadline) or now + mark_without_deadline_ms\n redis.call('SET', ikey, cjson.encode({d = digest, a = answer}), 'PXAT', base + mark_past_deadline_ms)\n end\n return answer\nend\nlocal function entry(key)\n local held = redis.call('HMGET', key, 'v', 'ver')\n if not held[1] then return false end\n local expires = redis.call('PEXPIRETIME', key)\n return {value = held[1], version = held[2], expiresAt = expires >= 0 and num(expires) or cjson.null}\nend\n\nlocal spec = cjson.decode(ARGV[1])\nlocal n = #KEYS\nlocal vkey = KEYS[n - 1]\nlocal ikey = ARGV[4] == '1' and KEYS[n] or ''\nlocal seen = guard(ikey, ARGV[3], ARGV[2])\nif seen then return out(seen) end\nfor index, c in ipairs(spec.conditions) do\n local ver = redis.call('HGET', KEYS[c.i], 'ver')\n local holds\n if c.absent then holds = not ver else holds = ver == c.version end\n if not holds then return out(remember(ikey, ARGV[3], cjson.encode({kind = 'conflict', index = index - 1}), ARGV[2])) end\nend\nlocal expiries = {}\nfor index, w in ipairs(spec.writes) do\n if not w.remove then expiries[index] = expiry(w.kind, w.arg, redis.call('PEXPIRETIME', KEYS[w.i])) end\nend\nlocal versions = {}\nfor index, w in ipairs(spec.writes) do\n if w.remove then\n redis.call('DEL', KEYS[w.i])\n versions[index] = cjson.null\n else\n versions[index] = store_value(KEYS[w.i], vkey, w.put, expiries[index])\n end\nend\nreturn out(remember(ikey, ARGV[3], cjson.encode({kind = 'committed', versions = versions, n = #spec.writes}), ARGV[2]))\n";
|
|
15
|
+
/** No keys. ARGV: deadline. An empty batch still honours its deadline. */
|
|
16
|
+
export declare const deadlineOnly = "\nlocal t = redis.call('TIME')\nlocal now = tonumber(t[1]) * 1000 + math.floor(tonumber(t[2]) / 1000)\nlocal function num(x) return string.format('%.0f', x) end\nlocal run_id = string.match(redis.call('INFO', 'server'), 'run_id:(%w+)')\n-- Every answer names the server it was computed on, so a confirmation is checked against it.\nlocal function out(answer) return run_id .. '\\n' .. answer end\n-- An entry is gone at its very expiry time by this script's clock; Redis would still hold it.\nfor _, key in ipairs(KEYS) do\n local expires = redis.call('PEXPIRETIME', key)\n if expires >= 0 and expires <= now then redis.call('DEL', key) end\nend\nlocal function next_version(vkey)\n local server = string.sub(run_id, 1, 12)\n .. string.sub(string.match(redis.call('INFO', 'replication'), 'master_replid:(%w+)'), 1, 12)\n local epoch = redis.call('HGET', vkey, 'epoch')\n if not epoch then\n epoch = t[1] .. string.format('%06d', tonumber(t[2]))\n redis.call('HSET', vkey, 'epoch', epoch)\n end\n local n = redis.call('HINCRBY', vkey, 'n', 1)\n redis.call('PEXPIRE', vkey, 86400000)\n return server .. '.' .. epoch .. '.' .. num(n)\nend\nlocal function expiry(kind, arg, current)\n if kind == 'after' then return now + tonumber(arg) end\n if kind == 'at' then return tonumber(arg) end\n if kind == 'never' then return nil end\n if kind == 'keep' then\n if current < 0 then return nil end\n return current\n end\n -- extend: never shorter than it was, and a key that never ends stays so.\n if current == -1 then return nil end\n return math.max(current, now + tonumber(arg))\nend\nlocal function store_value(key, vkey, value, expires)\n local v = next_version(vkey)\n redis.call('DEL', key)\n redis.call('HSET', key, 'v', value, 'ver', v)\n if expires ~= nil then redis.call('PEXPIREAT', key, expires) end\n return v\nend\nlocal function guard(ikey, digest, deadline)\n if ikey ~= '' then\n local seen = redis.call('GET', ikey)\n if seen then\n local record = cjson.decode(seen)\n if record.d == digest then return record.a end\n return cjson.encode({kind = 'reused'})\n end\n end\n if deadline ~= '' and now > tonumber(deadline) then return cjson.encode({kind = 'late'}) end\n return nil\nend\n-- A mark is kept a second past its deadline, or five minutes and a second without one, as store says.\nlocal mark_without_deadline_ms = 300000\nlocal mark_past_deadline_ms = 1000\nlocal function remember(ikey, digest, answer, deadline)\n if ikey ~= '' then\n local base = deadline ~= '' and tonumber(deadline) or now + mark_without_deadline_ms\n redis.call('SET', ikey, cjson.encode({d = digest, a = answer}), 'PXAT', base + mark_past_deadline_ms)\n end\n return answer\nend\nlocal function entry(key)\n local held = redis.call('HMGET', key, 'v', 'ver')\n if not held[1] then return false end\n local expires = redis.call('PEXPIRETIME', key)\n return {value = held[1], version = held[2], expiresAt = expires >= 0 and num(expires) or cjson.null}\nend\n\nif ARGV[1] ~= '' and now > tonumber(ARGV[1]) then return out(cjson.encode({kind = 'late'})) end\nreturn out(cjson.encode({kind = 'committed', versions = {}, n = 0}))\n";
|
|
17
|
+
/** KEYS: counter key, mark key. ARGV: window ms, limit, deadline, digest, has mark. Not versioned: it is hit hard. */
|
|
18
|
+
export declare const count = "\nlocal t = redis.call('TIME')\nlocal now = tonumber(t[1]) * 1000 + math.floor(tonumber(t[2]) / 1000)\nlocal function num(x) return string.format('%.0f', x) end\nlocal run_id = string.match(redis.call('INFO', 'server'), 'run_id:(%w+)')\n-- Every answer names the server it was computed on, so a confirmation is checked against it.\nlocal function out(answer) return run_id .. '\\n' .. answer end\n-- An entry is gone at its very expiry time by this script's clock; Redis would still hold it.\nfor _, key in ipairs(KEYS) do\n local expires = redis.call('PEXPIRETIME', key)\n if expires >= 0 and expires <= now then redis.call('DEL', key) end\nend\nlocal function next_version(vkey)\n local server = string.sub(run_id, 1, 12)\n .. string.sub(string.match(redis.call('INFO', 'replication'), 'master_replid:(%w+)'), 1, 12)\n local epoch = redis.call('HGET', vkey, 'epoch')\n if not epoch then\n epoch = t[1] .. string.format('%06d', tonumber(t[2]))\n redis.call('HSET', vkey, 'epoch', epoch)\n end\n local n = redis.call('HINCRBY', vkey, 'n', 1)\n redis.call('PEXPIRE', vkey, 86400000)\n return server .. '.' .. epoch .. '.' .. num(n)\nend\nlocal function expiry(kind, arg, current)\n if kind == 'after' then return now + tonumber(arg) end\n if kind == 'at' then return tonumber(arg) end\n if kind == 'never' then return nil end\n if kind == 'keep' then\n if current < 0 then return nil end\n return current\n end\n -- extend: never shorter than it was, and a key that never ends stays so.\n if current == -1 then return nil end\n return math.max(current, now + tonumber(arg))\nend\nlocal function store_value(key, vkey, value, expires)\n local v = next_version(vkey)\n redis.call('DEL', key)\n redis.call('HSET', key, 'v', value, 'ver', v)\n if expires ~= nil then redis.call('PEXPIREAT', key, expires) end\n return v\nend\nlocal function guard(ikey, digest, deadline)\n if ikey ~= '' then\n local seen = redis.call('GET', ikey)\n if seen then\n local record = cjson.decode(seen)\n if record.d == digest then return record.a end\n return cjson.encode({kind = 'reused'})\n end\n end\n if deadline ~= '' and now > tonumber(deadline) then return cjson.encode({kind = 'late'}) end\n return nil\nend\n-- A mark is kept a second past its deadline, or five minutes and a second without one, as store says.\nlocal mark_without_deadline_ms = 300000\nlocal mark_past_deadline_ms = 1000\nlocal function remember(ikey, digest, answer, deadline)\n if ikey ~= '' then\n local base = deadline ~= '' and tonumber(deadline) or now + mark_without_deadline_ms\n redis.call('SET', ikey, cjson.encode({d = digest, a = answer}), 'PXAT', base + mark_past_deadline_ms)\n end\n return answer\nend\nlocal function entry(key)\n local held = redis.call('HMGET', key, 'v', 'ver')\n if not held[1] then return false end\n local expires = redis.call('PEXPIRETIME', key)\n return {value = held[1], version = held[2], expiresAt = expires >= 0 and num(expires) or cjson.null}\nend\n\nlocal ikey = ARGV[5] == '1' and KEYS[2] or ''\nlocal seen = guard(ikey, ARGV[4], ARGV[3])\nif seen then return out(seen) end\nlocal ms, limit = tonumber(ARGV[1]), tonumber(ARGV[2])\nlocal current = redis.call('GET', KEYS[1])\nlocal answer\nif not current then\n if limit < 1 then\n answer = cjson.encode({kind = 'limited', resetAt = num(now + ms)})\n else\n redis.call('SET', KEYS[1], 1, 'PX', ms)\n answer = cjson.encode({kind = 'counted', count = 1, resetAt = num(now + ms)})\n end\nelse\n local reset = num(now + redis.call('PTTL', KEYS[1]))\n if tonumber(current) >= limit then\n answer = cjson.encode({kind = 'limited', resetAt = reset})\n else\n answer = cjson.encode({kind = 'counted', count = redis.call('INCR', KEYS[1]), resetAt = reset})\n end\nend\nreturn out(remember(ikey, ARGV[4], answer, ARGV[3]))\n";
|
|
19
|
+
/** KEYS: set key. ARGV: member, score, cap, kind, arg. A set's expiry never shrinks. */
|
|
20
|
+
export declare const setAdd = "\nlocal t = redis.call('TIME')\nlocal now = tonumber(t[1]) * 1000 + math.floor(tonumber(t[2]) / 1000)\nlocal function num(x) return string.format('%.0f', x) end\nlocal run_id = string.match(redis.call('INFO', 'server'), 'run_id:(%w+)')\n-- Every answer names the server it was computed on, so a confirmation is checked against it.\nlocal function out(answer) return run_id .. '\\n' .. answer end\n-- An entry is gone at its very expiry time by this script's clock; Redis would still hold it.\nfor _, key in ipairs(KEYS) do\n local expires = redis.call('PEXPIRETIME', key)\n if expires >= 0 and expires <= now then redis.call('DEL', key) end\nend\nlocal function next_version(vkey)\n local server = string.sub(run_id, 1, 12)\n .. string.sub(string.match(redis.call('INFO', 'replication'), 'master_replid:(%w+)'), 1, 12)\n local epoch = redis.call('HGET', vkey, 'epoch')\n if not epoch then\n epoch = t[1] .. string.format('%06d', tonumber(t[2]))\n redis.call('HSET', vkey, 'epoch', epoch)\n end\n local n = redis.call('HINCRBY', vkey, 'n', 1)\n redis.call('PEXPIRE', vkey, 86400000)\n return server .. '.' .. epoch .. '.' .. num(n)\nend\nlocal function expiry(kind, arg, current)\n if kind == 'after' then return now + tonumber(arg) end\n if kind == 'at' then return tonumber(arg) end\n if kind == 'never' then return nil end\n if kind == 'keep' then\n if current < 0 then return nil end\n return current\n end\n -- extend: never shorter than it was, and a key that never ends stays so.\n if current == -1 then return nil end\n return math.max(current, now + tonumber(arg))\nend\nlocal function store_value(key, vkey, value, expires)\n local v = next_version(vkey)\n redis.call('DEL', key)\n redis.call('HSET', key, 'v', value, 'ver', v)\n if expires ~= nil then redis.call('PEXPIREAT', key, expires) end\n return v\nend\nlocal function guard(ikey, digest, deadline)\n if ikey ~= '' then\n local seen = redis.call('GET', ikey)\n if seen then\n local record = cjson.decode(seen)\n if record.d == digest then return record.a end\n return cjson.encode({kind = 'reused'})\n end\n end\n if deadline ~= '' and now > tonumber(deadline) then return cjson.encode({kind = 'late'}) end\n return nil\nend\n-- A mark is kept a second past its deadline, or five minutes and a second without one, as store says.\nlocal mark_without_deadline_ms = 300000\nlocal mark_past_deadline_ms = 1000\nlocal function remember(ikey, digest, answer, deadline)\n if ikey ~= '' then\n local base = deadline ~= '' and tonumber(deadline) or now + mark_without_deadline_ms\n redis.call('SET', ikey, cjson.encode({d = digest, a = answer}), 'PXAT', base + mark_past_deadline_ms)\n end\n return answer\nend\nlocal function entry(key)\n local held = redis.call('HMGET', key, 'v', 'ver')\n if not held[1] then return false end\n local expires = redis.call('PEXPIRETIME', key)\n return {value = held[1], version = held[2], expiresAt = expires >= 0 and num(expires) or cjson.null}\nend\n\nlocal key = KEYS[1]\nredis.call('ZREMRANGEBYSCORE', key, '-inf', num(now))\nlocal fresh = redis.call('EXISTS', key) == 0\nlocal current = redis.call('PEXPIRETIME', key)\nlocal proposed = expiry(ARGV[4], ARGV[5], fresh and -2 or current)\nlocal final\nif fresh then final = proposed\nelseif current == -1 or proposed == nil then final = nil\nelse final = math.max(current, proposed) end\nredis.call('ZADD', key, 'GT', ARGV[2], ARGV[1])\nlocal evicted = {}\nlocal over = redis.call('ZCARD', key) - tonumber(ARGV[3])\nif over > 0 then\n local popped = redis.call('ZPOPMIN', key, over)\n for i = 1, #popped, 2 do table.insert(evicted, popped[i]) end\nend\nif redis.call('EXISTS', key) == 1 then\n if final == nil then redis.call('PERSIST', key) else redis.call('PEXPIREAT', key, final) end\nend\nreturn out(cjson.encode({evicted = evicted, n = #evicted}))\n";
|
|
21
|
+
/** KEYS: set key. */
|
|
22
|
+
export declare const setMembers = "\nlocal t = redis.call('TIME')\nlocal now = tonumber(t[1]) * 1000 + math.floor(tonumber(t[2]) / 1000)\nlocal function num(x) return string.format('%.0f', x) end\nlocal run_id = string.match(redis.call('INFO', 'server'), 'run_id:(%w+)')\n-- Every answer names the server it was computed on, so a confirmation is checked against it.\nlocal function out(answer) return run_id .. '\\n' .. answer end\n-- An entry is gone at its very expiry time by this script's clock; Redis would still hold it.\nfor _, key in ipairs(KEYS) do\n local expires = redis.call('PEXPIRETIME', key)\n if expires >= 0 and expires <= now then redis.call('DEL', key) end\nend\nlocal function next_version(vkey)\n local server = string.sub(run_id, 1, 12)\n .. string.sub(string.match(redis.call('INFO', 'replication'), 'master_replid:(%w+)'), 1, 12)\n local epoch = redis.call('HGET', vkey, 'epoch')\n if not epoch then\n epoch = t[1] .. string.format('%06d', tonumber(t[2]))\n redis.call('HSET', vkey, 'epoch', epoch)\n end\n local n = redis.call('HINCRBY', vkey, 'n', 1)\n redis.call('PEXPIRE', vkey, 86400000)\n return server .. '.' .. epoch .. '.' .. num(n)\nend\nlocal function expiry(kind, arg, current)\n if kind == 'after' then return now + tonumber(arg) end\n if kind == 'at' then return tonumber(arg) end\n if kind == 'never' then return nil end\n if kind == 'keep' then\n if current < 0 then return nil end\n return current\n end\n -- extend: never shorter than it was, and a key that never ends stays so.\n if current == -1 then return nil end\n return math.max(current, now + tonumber(arg))\nend\nlocal function store_value(key, vkey, value, expires)\n local v = next_version(vkey)\n redis.call('DEL', key)\n redis.call('HSET', key, 'v', value, 'ver', v)\n if expires ~= nil then redis.call('PEXPIREAT', key, expires) end\n return v\nend\nlocal function guard(ikey, digest, deadline)\n if ikey ~= '' then\n local seen = redis.call('GET', ikey)\n if seen then\n local record = cjson.decode(seen)\n if record.d == digest then return record.a end\n return cjson.encode({kind = 'reused'})\n end\n end\n if deadline ~= '' and now > tonumber(deadline) then return cjson.encode({kind = 'late'}) end\n return nil\nend\n-- A mark is kept a second past its deadline, or five minutes and a second without one, as store says.\nlocal mark_without_deadline_ms = 300000\nlocal mark_past_deadline_ms = 1000\nlocal function remember(ikey, digest, answer, deadline)\n if ikey ~= '' then\n local base = deadline ~= '' and tonumber(deadline) or now + mark_without_deadline_ms\n redis.call('SET', ikey, cjson.encode({d = digest, a = answer}), 'PXAT', base + mark_past_deadline_ms)\n end\n return answer\nend\nlocal function entry(key)\n local held = redis.call('HMGET', key, 'v', 'ver')\n if not held[1] then return false end\n local expires = redis.call('PEXPIRETIME', key)\n return {value = held[1], version = held[2], expiresAt = expires >= 0 and num(expires) or cjson.null}\nend\n\nredis.call('ZREMRANGEBYSCORE', KEYS[1], '-inf', num(now))\nreturn out(cjson.encode({now = num(now), members = redis.call('ZRANGE', KEYS[1], 0, -1, 'WITHSCORES')}))\n";
|
|
23
|
+
/** KEYS: set key. ARGV: member. */
|
|
24
|
+
export declare const setRemove = "\nlocal t = redis.call('TIME')\nlocal now = tonumber(t[1]) * 1000 + math.floor(tonumber(t[2]) / 1000)\nlocal function num(x) return string.format('%.0f', x) end\nlocal run_id = string.match(redis.call('INFO', 'server'), 'run_id:(%w+)')\n-- Every answer names the server it was computed on, so a confirmation is checked against it.\nlocal function out(answer) return run_id .. '\\n' .. answer end\n-- An entry is gone at its very expiry time by this script's clock; Redis would still hold it.\nfor _, key in ipairs(KEYS) do\n local expires = redis.call('PEXPIRETIME', key)\n if expires >= 0 and expires <= now then redis.call('DEL', key) end\nend\nlocal function next_version(vkey)\n local server = string.sub(run_id, 1, 12)\n .. string.sub(string.match(redis.call('INFO', 'replication'), 'master_replid:(%w+)'), 1, 12)\n local epoch = redis.call('HGET', vkey, 'epoch')\n if not epoch then\n epoch = t[1] .. string.format('%06d', tonumber(t[2]))\n redis.call('HSET', vkey, 'epoch', epoch)\n end\n local n = redis.call('HINCRBY', vkey, 'n', 1)\n redis.call('PEXPIRE', vkey, 86400000)\n return server .. '.' .. epoch .. '.' .. num(n)\nend\nlocal function expiry(kind, arg, current)\n if kind == 'after' then return now + tonumber(arg) end\n if kind == 'at' then return tonumber(arg) end\n if kind == 'never' then return nil end\n if kind == 'keep' then\n if current < 0 then return nil end\n return current\n end\n -- extend: never shorter than it was, and a key that never ends stays so.\n if current == -1 then return nil end\n return math.max(current, now + tonumber(arg))\nend\nlocal function store_value(key, vkey, value, expires)\n local v = next_version(vkey)\n redis.call('DEL', key)\n redis.call('HSET', key, 'v', value, 'ver', v)\n if expires ~= nil then redis.call('PEXPIREAT', key, expires) end\n return v\nend\nlocal function guard(ikey, digest, deadline)\n if ikey ~= '' then\n local seen = redis.call('GET', ikey)\n if seen then\n local record = cjson.decode(seen)\n if record.d == digest then return record.a end\n return cjson.encode({kind = 'reused'})\n end\n end\n if deadline ~= '' and now > tonumber(deadline) then return cjson.encode({kind = 'late'}) end\n return nil\nend\n-- A mark is kept a second past its deadline, or five minutes and a second without one, as store says.\nlocal mark_without_deadline_ms = 300000\nlocal mark_past_deadline_ms = 1000\nlocal function remember(ikey, digest, answer, deadline)\n if ikey ~= '' then\n local base = deadline ~= '' and tonumber(deadline) or now + mark_without_deadline_ms\n redis.call('SET', ikey, cjson.encode({d = digest, a = answer}), 'PXAT', base + mark_past_deadline_ms)\n end\n return answer\nend\nlocal function entry(key)\n local held = redis.call('HMGET', key, 'v', 'ver')\n if not held[1] then return false end\n local expires = redis.call('PEXPIRETIME', key)\n return {value = held[1], version = held[2], expiresAt = expires >= 0 and num(expires) or cjson.null}\nend\n\nredis.call('ZREM', KEYS[1], ARGV[1])\nreturn out(cjson.encode({kind = 'written'}))\n";
|
|
25
|
+
/** The store clock's present time. */
|
|
26
|
+
export declare const now = "\nlocal t = redis.call('TIME')\nlocal now = tonumber(t[1]) * 1000 + math.floor(tonumber(t[2]) / 1000)\nlocal function num(x) return string.format('%.0f', x) end\nlocal run_id = string.match(redis.call('INFO', 'server'), 'run_id:(%w+)')\n-- Every answer names the server it was computed on, so a confirmation is checked against it.\nlocal function out(answer) return run_id .. '\\n' .. answer end\n-- An entry is gone at its very expiry time by this script's clock; Redis would still hold it.\nfor _, key in ipairs(KEYS) do\n local expires = redis.call('PEXPIRETIME', key)\n if expires >= 0 and expires <= now then redis.call('DEL', key) end\nend\nlocal function next_version(vkey)\n local server = string.sub(run_id, 1, 12)\n .. string.sub(string.match(redis.call('INFO', 'replication'), 'master_replid:(%w+)'), 1, 12)\n local epoch = redis.call('HGET', vkey, 'epoch')\n if not epoch then\n epoch = t[1] .. string.format('%06d', tonumber(t[2]))\n redis.call('HSET', vkey, 'epoch', epoch)\n end\n local n = redis.call('HINCRBY', vkey, 'n', 1)\n redis.call('PEXPIRE', vkey, 86400000)\n return server .. '.' .. epoch .. '.' .. num(n)\nend\nlocal function expiry(kind, arg, current)\n if kind == 'after' then return now + tonumber(arg) end\n if kind == 'at' then return tonumber(arg) end\n if kind == 'never' then return nil end\n if kind == 'keep' then\n if current < 0 then return nil end\n return current\n end\n -- extend: never shorter than it was, and a key that never ends stays so.\n if current == -1 then return nil end\n return math.max(current, now + tonumber(arg))\nend\nlocal function store_value(key, vkey, value, expires)\n local v = next_version(vkey)\n redis.call('DEL', key)\n redis.call('HSET', key, 'v', value, 'ver', v)\n if expires ~= nil then redis.call('PEXPIREAT', key, expires) end\n return v\nend\nlocal function guard(ikey, digest, deadline)\n if ikey ~= '' then\n local seen = redis.call('GET', ikey)\n if seen then\n local record = cjson.decode(seen)\n if record.d == digest then return record.a end\n return cjson.encode({kind = 'reused'})\n end\n end\n if deadline ~= '' and now > tonumber(deadline) then return cjson.encode({kind = 'late'}) end\n return nil\nend\n-- A mark is kept a second past its deadline, or five minutes and a second without one, as store says.\nlocal mark_without_deadline_ms = 300000\nlocal mark_past_deadline_ms = 1000\nlocal function remember(ikey, digest, answer, deadline)\n if ikey ~= '' then\n local base = deadline ~= '' and tonumber(deadline) or now + mark_without_deadline_ms\n redis.call('SET', ikey, cjson.encode({d = digest, a = answer}), 'PXAT', base + mark_past_deadline_ms)\n end\n return answer\nend\nlocal function entry(key)\n local held = redis.call('HMGET', key, 'v', 'ver')\n if not held[1] then return false end\n local expires = redis.call('PEXPIRETIME', key)\n return {value = held[1], version = held[2], expiresAt = expires >= 0 and num(expires) or cjson.null}\nend\n\nreturn out(cjson.encode({now = num(now)}))\n";
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared prelude: store time, versions, expiry and idempotency. Every input has been checked at
|
|
3
|
+
* the store contract boundary, so nothing below fails after the first write.
|
|
4
|
+
*
|
|
5
|
+
* A version is "<server>.<epoch>.<n>". <server> joins the run id (new on every restart) and the
|
|
6
|
+
* replication id (new when a replica is promoted), so a counter rolled back by a restart or a
|
|
7
|
+
* failover never hands out a version seen before; <epoch> is the store time when the counter
|
|
8
|
+
* was created, so a counter that expired and came back starts afresh too. The counter lives a
|
|
9
|
+
* day past its last use. Numbers go out as strings, since cjson keeps only 14 digits.
|
|
10
|
+
*/
|
|
11
|
+
const prelude = `
|
|
12
|
+
local t = redis.call('TIME')
|
|
13
|
+
local now = tonumber(t[1]) * 1000 + math.floor(tonumber(t[2]) / 1000)
|
|
14
|
+
local function num(x) return string.format('%.0f', x) end
|
|
15
|
+
local run_id = string.match(redis.call('INFO', 'server'), 'run_id:(%w+)')
|
|
16
|
+
-- Every answer names the server it was computed on, so a confirmation is checked against it.
|
|
17
|
+
local function out(answer) return run_id .. '\\n' .. answer end
|
|
18
|
+
-- An entry is gone at its very expiry time by this script's clock; Redis would still hold it.
|
|
19
|
+
for _, key in ipairs(KEYS) do
|
|
20
|
+
local expires = redis.call('PEXPIRETIME', key)
|
|
21
|
+
if expires >= 0 and expires <= now then redis.call('DEL', key) end
|
|
22
|
+
end
|
|
23
|
+
local function next_version(vkey)
|
|
24
|
+
local server = string.sub(run_id, 1, 12)
|
|
25
|
+
.. string.sub(string.match(redis.call('INFO', 'replication'), 'master_replid:(%w+)'), 1, 12)
|
|
26
|
+
local epoch = redis.call('HGET', vkey, 'epoch')
|
|
27
|
+
if not epoch then
|
|
28
|
+
epoch = t[1] .. string.format('%06d', tonumber(t[2]))
|
|
29
|
+
redis.call('HSET', vkey, 'epoch', epoch)
|
|
30
|
+
end
|
|
31
|
+
local n = redis.call('HINCRBY', vkey, 'n', 1)
|
|
32
|
+
redis.call('PEXPIRE', vkey, 86400000)
|
|
33
|
+
return server .. '.' .. epoch .. '.' .. num(n)
|
|
34
|
+
end
|
|
35
|
+
local function expiry(kind, arg, current)
|
|
36
|
+
if kind == 'after' then return now + tonumber(arg) end
|
|
37
|
+
if kind == 'at' then return tonumber(arg) end
|
|
38
|
+
if kind == 'never' then return nil end
|
|
39
|
+
if kind == 'keep' then
|
|
40
|
+
if current < 0 then return nil end
|
|
41
|
+
return current
|
|
42
|
+
end
|
|
43
|
+
-- extend: never shorter than it was, and a key that never ends stays so.
|
|
44
|
+
if current == -1 then return nil end
|
|
45
|
+
return math.max(current, now + tonumber(arg))
|
|
46
|
+
end
|
|
47
|
+
local function store_value(key, vkey, value, expires)
|
|
48
|
+
local v = next_version(vkey)
|
|
49
|
+
redis.call('DEL', key)
|
|
50
|
+
redis.call('HSET', key, 'v', value, 'ver', v)
|
|
51
|
+
if expires ~= nil then redis.call('PEXPIREAT', key, expires) end
|
|
52
|
+
return v
|
|
53
|
+
end
|
|
54
|
+
local function guard(ikey, digest, deadline)
|
|
55
|
+
if ikey ~= '' then
|
|
56
|
+
local seen = redis.call('GET', ikey)
|
|
57
|
+
if seen then
|
|
58
|
+
local record = cjson.decode(seen)
|
|
59
|
+
if record.d == digest then return record.a end
|
|
60
|
+
return cjson.encode({kind = 'reused'})
|
|
61
|
+
end
|
|
62
|
+
end
|
|
63
|
+
if deadline ~= '' and now > tonumber(deadline) then return cjson.encode({kind = 'late'}) end
|
|
64
|
+
return nil
|
|
65
|
+
end
|
|
66
|
+
-- A mark is kept a second past its deadline, or five minutes and a second without one, as store says.
|
|
67
|
+
local mark_without_deadline_ms = 300000
|
|
68
|
+
local mark_past_deadline_ms = 1000
|
|
69
|
+
local function remember(ikey, digest, answer, deadline)
|
|
70
|
+
if ikey ~= '' then
|
|
71
|
+
local base = deadline ~= '' and tonumber(deadline) or now + mark_without_deadline_ms
|
|
72
|
+
redis.call('SET', ikey, cjson.encode({d = digest, a = answer}), 'PXAT', base + mark_past_deadline_ms)
|
|
73
|
+
end
|
|
74
|
+
return answer
|
|
75
|
+
end
|
|
76
|
+
local function entry(key)
|
|
77
|
+
local held = redis.call('HMGET', key, 'v', 'ver')
|
|
78
|
+
if not held[1] then return false end
|
|
79
|
+
local expires = redis.call('PEXPIRETIME', key)
|
|
80
|
+
return {value = held[1], version = held[2], expiresAt = expires >= 0 and num(expires) or cjson.null}
|
|
81
|
+
end
|
|
82
|
+
`;
|
|
83
|
+
/** KEYS: key, version key, mark key. ARGV: mode, value, expected, kind, arg, deadline, digest, has mark. */
|
|
84
|
+
export const write = `${prelude}
|
|
85
|
+
local key, vkey, ikey = KEYS[1], KEYS[2], ARGV[8] == '1' and KEYS[3] or ''
|
|
86
|
+
local seen = guard(ikey, ARGV[7], ARGV[6])
|
|
87
|
+
if seen then return out(seen) end
|
|
88
|
+
local mode = ARGV[1]
|
|
89
|
+
local exists = redis.call('EXISTS', key) == 1
|
|
90
|
+
local answer
|
|
91
|
+
if mode == 'putIfAbsent' and exists then
|
|
92
|
+
local ttl = redis.call('PTTL', key)
|
|
93
|
+
answer = cjson.encode({kind = 'exists', remainingMs = ttl >= 0 and num(ttl) or cjson.null})
|
|
94
|
+
elseif mode == 'replaceIf' and not exists then
|
|
95
|
+
answer = cjson.encode({kind = 'missing'})
|
|
96
|
+
elseif mode == 'replaceIf' and redis.call('HGET', key, 'ver') ~= ARGV[3] then
|
|
97
|
+
answer = cjson.encode({kind = 'conflict'})
|
|
98
|
+
else
|
|
99
|
+
local expires = expiry(ARGV[4], ARGV[5], redis.call('PEXPIRETIME', key))
|
|
100
|
+
answer = cjson.encode({kind = 'written', version = store_value(key, vkey, ARGV[2], expires)})
|
|
101
|
+
end
|
|
102
|
+
return out(remember(ikey, ARGV[7], answer, ARGV[6]))
|
|
103
|
+
`;
|
|
104
|
+
/** KEYS: key, mark key. ARGV: by ('version'|'value'), expected, deadline, digest, has mark. */
|
|
105
|
+
export const removeIf = `${prelude}
|
|
106
|
+
local key, ikey = KEYS[1], ARGV[5] == '1' and KEYS[2] or ''
|
|
107
|
+
local seen = guard(ikey, ARGV[4], ARGV[3])
|
|
108
|
+
if seen then return out(seen) end
|
|
109
|
+
local held = entry(KEYS[1])
|
|
110
|
+
local answer
|
|
111
|
+
if not held then
|
|
112
|
+
answer = cjson.encode({kind = 'missing'})
|
|
113
|
+
elseif (ARGV[1] == 'version' and held.version ~= ARGV[2]) or (ARGV[1] == 'value' and held.value ~= ARGV[2]) then
|
|
114
|
+
answer = cjson.encode({kind = 'conflict'})
|
|
115
|
+
else
|
|
116
|
+
redis.call('DEL', key)
|
|
117
|
+
answer = cjson.encode({kind = 'removed', old = held})
|
|
118
|
+
end
|
|
119
|
+
return out(remember(ikey, ARGV[4], answer, ARGV[3]))
|
|
120
|
+
`;
|
|
121
|
+
/** KEYS: the keys to read. */
|
|
122
|
+
export const read = `${prelude}
|
|
123
|
+
local entries = {}
|
|
124
|
+
for i, key in ipairs(KEYS) do entries[i] = entry(key) end
|
|
125
|
+
return out(cjson.encode({now = num(now), entries = entries, n = #KEYS}))
|
|
126
|
+
`;
|
|
127
|
+
/** KEYS: key, mark key. ARGV: deadline, digest, has mark. */
|
|
128
|
+
export const take = `${prelude}
|
|
129
|
+
local ikey = ARGV[3] == '1' and KEYS[2] or ''
|
|
130
|
+
local seen = guard(ikey, ARGV[2], ARGV[1])
|
|
131
|
+
if seen then return out(seen) end
|
|
132
|
+
local held = entry(KEYS[1])
|
|
133
|
+
local answer
|
|
134
|
+
if not held then
|
|
135
|
+
answer = cjson.encode({kind = 'missing'})
|
|
136
|
+
else
|
|
137
|
+
redis.call('DEL', KEYS[1])
|
|
138
|
+
answer = cjson.encode({kind = 'taken', entry = held})
|
|
139
|
+
end
|
|
140
|
+
return out(remember(ikey, ARGV[2], answer, ARGV[1]))
|
|
141
|
+
`;
|
|
142
|
+
/**
|
|
143
|
+
* KEYS: the batch keys, then the version key, then the mark key.
|
|
144
|
+
* ARGV: spec JSON {conditions = [{i, version|absent}], writes = [{i, put, kind, arg}|{i, remove}]},
|
|
145
|
+
* deadline, digest, has mark.
|
|
146
|
+
*/
|
|
147
|
+
export const batch = `${prelude}
|
|
148
|
+
local spec = cjson.decode(ARGV[1])
|
|
149
|
+
local n = #KEYS
|
|
150
|
+
local vkey = KEYS[n - 1]
|
|
151
|
+
local ikey = ARGV[4] == '1' and KEYS[n] or ''
|
|
152
|
+
local seen = guard(ikey, ARGV[3], ARGV[2])
|
|
153
|
+
if seen then return out(seen) end
|
|
154
|
+
for index, c in ipairs(spec.conditions) do
|
|
155
|
+
local ver = redis.call('HGET', KEYS[c.i], 'ver')
|
|
156
|
+
local holds
|
|
157
|
+
if c.absent then holds = not ver else holds = ver == c.version end
|
|
158
|
+
if not holds then return out(remember(ikey, ARGV[3], cjson.encode({kind = 'conflict', index = index - 1}), ARGV[2])) end
|
|
159
|
+
end
|
|
160
|
+
local expiries = {}
|
|
161
|
+
for index, w in ipairs(spec.writes) do
|
|
162
|
+
if not w.remove then expiries[index] = expiry(w.kind, w.arg, redis.call('PEXPIRETIME', KEYS[w.i])) end
|
|
163
|
+
end
|
|
164
|
+
local versions = {}
|
|
165
|
+
for index, w in ipairs(spec.writes) do
|
|
166
|
+
if w.remove then
|
|
167
|
+
redis.call('DEL', KEYS[w.i])
|
|
168
|
+
versions[index] = cjson.null
|
|
169
|
+
else
|
|
170
|
+
versions[index] = store_value(KEYS[w.i], vkey, w.put, expiries[index])
|
|
171
|
+
end
|
|
172
|
+
end
|
|
173
|
+
return out(remember(ikey, ARGV[3], cjson.encode({kind = 'committed', versions = versions, n = #spec.writes}), ARGV[2]))
|
|
174
|
+
`;
|
|
175
|
+
/** No keys. ARGV: deadline. An empty batch still honours its deadline. */
|
|
176
|
+
export const deadlineOnly = `${prelude}
|
|
177
|
+
if ARGV[1] ~= '' and now > tonumber(ARGV[1]) then return out(cjson.encode({kind = 'late'})) end
|
|
178
|
+
return out(cjson.encode({kind = 'committed', versions = {}, n = 0}))
|
|
179
|
+
`;
|
|
180
|
+
/** KEYS: counter key, mark key. ARGV: window ms, limit, deadline, digest, has mark. Not versioned: it is hit hard. */
|
|
181
|
+
export const count = `${prelude}
|
|
182
|
+
local ikey = ARGV[5] == '1' and KEYS[2] or ''
|
|
183
|
+
local seen = guard(ikey, ARGV[4], ARGV[3])
|
|
184
|
+
if seen then return out(seen) end
|
|
185
|
+
local ms, limit = tonumber(ARGV[1]), tonumber(ARGV[2])
|
|
186
|
+
local current = redis.call('GET', KEYS[1])
|
|
187
|
+
local answer
|
|
188
|
+
if not current then
|
|
189
|
+
if limit < 1 then
|
|
190
|
+
answer = cjson.encode({kind = 'limited', resetAt = num(now + ms)})
|
|
191
|
+
else
|
|
192
|
+
redis.call('SET', KEYS[1], 1, 'PX', ms)
|
|
193
|
+
answer = cjson.encode({kind = 'counted', count = 1, resetAt = num(now + ms)})
|
|
194
|
+
end
|
|
195
|
+
else
|
|
196
|
+
local reset = num(now + redis.call('PTTL', KEYS[1]))
|
|
197
|
+
if tonumber(current) >= limit then
|
|
198
|
+
answer = cjson.encode({kind = 'limited', resetAt = reset})
|
|
199
|
+
else
|
|
200
|
+
answer = cjson.encode({kind = 'counted', count = redis.call('INCR', KEYS[1]), resetAt = reset})
|
|
201
|
+
end
|
|
202
|
+
end
|
|
203
|
+
return out(remember(ikey, ARGV[4], answer, ARGV[3]))
|
|
204
|
+
`;
|
|
205
|
+
/** KEYS: set key. ARGV: member, score, cap, kind, arg. A set's expiry never shrinks. */
|
|
206
|
+
export const setAdd = `${prelude}
|
|
207
|
+
local key = KEYS[1]
|
|
208
|
+
redis.call('ZREMRANGEBYSCORE', key, '-inf', num(now))
|
|
209
|
+
local fresh = redis.call('EXISTS', key) == 0
|
|
210
|
+
local current = redis.call('PEXPIRETIME', key)
|
|
211
|
+
local proposed = expiry(ARGV[4], ARGV[5], fresh and -2 or current)
|
|
212
|
+
local final
|
|
213
|
+
if fresh then final = proposed
|
|
214
|
+
elseif current == -1 or proposed == nil then final = nil
|
|
215
|
+
else final = math.max(current, proposed) end
|
|
216
|
+
redis.call('ZADD', key, 'GT', ARGV[2], ARGV[1])
|
|
217
|
+
local evicted = {}
|
|
218
|
+
local over = redis.call('ZCARD', key) - tonumber(ARGV[3])
|
|
219
|
+
if over > 0 then
|
|
220
|
+
local popped = redis.call('ZPOPMIN', key, over)
|
|
221
|
+
for i = 1, #popped, 2 do table.insert(evicted, popped[i]) end
|
|
222
|
+
end
|
|
223
|
+
if redis.call('EXISTS', key) == 1 then
|
|
224
|
+
if final == nil then redis.call('PERSIST', key) else redis.call('PEXPIREAT', key, final) end
|
|
225
|
+
end
|
|
226
|
+
return out(cjson.encode({evicted = evicted, n = #evicted}))
|
|
227
|
+
`;
|
|
228
|
+
/** KEYS: set key. */
|
|
229
|
+
export const setMembers = `${prelude}
|
|
230
|
+
redis.call('ZREMRANGEBYSCORE', KEYS[1], '-inf', num(now))
|
|
231
|
+
return out(cjson.encode({now = num(now), members = redis.call('ZRANGE', KEYS[1], 0, -1, 'WITHSCORES')}))
|
|
232
|
+
`;
|
|
233
|
+
/** KEYS: set key. ARGV: member. */
|
|
234
|
+
export const setRemove = `${prelude}
|
|
235
|
+
redis.call('ZREM', KEYS[1], ARGV[1])
|
|
236
|
+
return out(cjson.encode({kind = 'written'}))
|
|
237
|
+
`;
|
|
238
|
+
/** The store clock's present time. */
|
|
239
|
+
export const now = `${prelude}
|
|
240
|
+
return out(cjson.encode({now = num(now)}))
|
|
241
|
+
`;
|