@convex-dev/sharded-counter 0.1.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.
Files changed (63) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +246 -0
  3. package/dist/commonjs/client/index.d.ts +37 -0
  4. package/dist/commonjs/client/index.d.ts.map +1 -0
  5. package/dist/commonjs/client/index.js +30 -0
  6. package/dist/commonjs/client/index.js.map +1 -0
  7. package/dist/commonjs/component/_generated/api.d.ts +14 -0
  8. package/dist/commonjs/component/_generated/api.d.ts.map +1 -0
  9. package/dist/commonjs/component/_generated/api.js +24 -0
  10. package/dist/commonjs/component/_generated/api.js.map +1 -0
  11. package/dist/commonjs/component/_generated/server.d.ts +64 -0
  12. package/dist/commonjs/component/_generated/server.d.ts.map +1 -0
  13. package/dist/commonjs/component/_generated/server.js +76 -0
  14. package/dist/commonjs/component/_generated/server.js.map +1 -0
  15. package/dist/commonjs/component/convex.config.d.ts +3 -0
  16. package/dist/commonjs/component/convex.config.d.ts.map +1 -0
  17. package/dist/commonjs/component/convex.config.js +3 -0
  18. package/dist/commonjs/component/convex.config.js.map +1 -0
  19. package/dist/commonjs/component/public.d.ts +10 -0
  20. package/dist/commonjs/component/public.d.ts.map +1 -0
  21. package/dist/commonjs/component/public.js +42 -0
  22. package/dist/commonjs/component/public.js.map +1 -0
  23. package/dist/commonjs/component/schema.d.ts +15 -0
  24. package/dist/commonjs/component/schema.d.ts.map +1 -0
  25. package/dist/commonjs/component/schema.js +10 -0
  26. package/dist/commonjs/component/schema.js.map +1 -0
  27. package/dist/commonjs/package.json +3 -0
  28. package/dist/esm/client/index.d.ts +37 -0
  29. package/dist/esm/client/index.d.ts.map +1 -0
  30. package/dist/esm/client/index.js +30 -0
  31. package/dist/esm/client/index.js.map +1 -0
  32. package/dist/esm/component/_generated/api.d.ts +14 -0
  33. package/dist/esm/component/_generated/api.d.ts.map +1 -0
  34. package/dist/esm/component/_generated/api.js +24 -0
  35. package/dist/esm/component/_generated/api.js.map +1 -0
  36. package/dist/esm/component/_generated/server.d.ts +64 -0
  37. package/dist/esm/component/_generated/server.d.ts.map +1 -0
  38. package/dist/esm/component/_generated/server.js +76 -0
  39. package/dist/esm/component/_generated/server.js.map +1 -0
  40. package/dist/esm/component/convex.config.d.ts +3 -0
  41. package/dist/esm/component/convex.config.d.ts.map +1 -0
  42. package/dist/esm/component/convex.config.js +3 -0
  43. package/dist/esm/component/convex.config.js.map +1 -0
  44. package/dist/esm/component/public.d.ts +10 -0
  45. package/dist/esm/component/public.d.ts.map +1 -0
  46. package/dist/esm/component/public.js +42 -0
  47. package/dist/esm/component/public.js.map +1 -0
  48. package/dist/esm/component/schema.d.ts +15 -0
  49. package/dist/esm/component/schema.d.ts.map +1 -0
  50. package/dist/esm/component/schema.js +10 -0
  51. package/dist/esm/component/schema.js.map +1 -0
  52. package/dist/esm/package.json +3 -0
  53. package/package.json +76 -0
  54. package/src/client/index.ts +82 -0
  55. package/src/component/_generated/api.d.ts +58 -0
  56. package/src/component/_generated/api.js +27 -0
  57. package/src/component/_generated/dataModel.d.ts +64 -0
  58. package/src/component/_generated/server.d.ts +153 -0
  59. package/src/component/_generated/server.js +94 -0
  60. package/src/component/convex.config.ts +3 -0
  61. package/src/component/counter.test.ts +45 -0
  62. package/src/component/public.ts +43 -0
  63. package/src/component/schema.ts +10 -0
package/package.json ADDED
@@ -0,0 +1,76 @@
1
+ {
2
+ "name": "@convex-dev/sharded-counter",
3
+ "description": "A sharded counter component for Convex.",
4
+ "repository": "github:get-convex/sharded-counter",
5
+ "homepage": "https://github.com/get-convex/sharded-counter#readme",
6
+ "bugs": {
7
+ "email": "support@convex.dev",
8
+ "url": "https://github.com/get-convex/sharded-counter/issues"
9
+ },
10
+ "version": "0.1.1",
11
+ "license": "Apache-2.0",
12
+ "keywords": [
13
+ "convex",
14
+ "count",
15
+ "component"
16
+ ],
17
+ "type": "module",
18
+ "scripts": {
19
+ "build": "npm run build:esm && npm run build:cjs",
20
+ "build:esm": "tsc --project ./esm.json && echo '{\\n \"type\": \"module\"\\n}' > dist/esm/package.json",
21
+ "build:cjs": "tsc --project ./commonjs.json && echo '{\\n \"type\": \"commonjs\"\\n}' > dist/commonjs/package.json",
22
+ "dev": "cd example; npm run dev",
23
+ "typecheck": "tsc --noEmit",
24
+ "prepare": "npm run build",
25
+ "prepack": "node node10stubs.mjs",
26
+ "postpack": "node node10stubs.mjs --cleanup",
27
+ "test": "vitest run",
28
+ "test:debug": "vitest --inspect-brk --no-file-parallelism",
29
+ "test:coverage": "vitest run --coverage --coverage.reporter=text"
30
+ },
31
+ "files": [
32
+ "dist",
33
+ "src",
34
+ "react"
35
+ ],
36
+ "exports": {
37
+ "./package.json": "./package.json",
38
+ ".": {
39
+ "import": {
40
+ "@convex-dev/component-source": "./src/client/index.ts",
41
+ "types": "./dist/esm/client/index.d.ts",
42
+ "default": "./dist/esm/client/index.js"
43
+ },
44
+ "require": {
45
+ "@convex-dev/component-source": "./src/client/index.ts",
46
+ "types": "./dist/commonjs/client/index.d.ts",
47
+ "default": "./dist/commonjs/client/index.js"
48
+ }
49
+ },
50
+ "./convex.config": {
51
+ "import": {
52
+ "@convex-dev/component-source": "./src/component/convex.config.ts",
53
+ "types": "./dist/esm/component/convex.config.d.ts",
54
+ "default": "./dist/esm/component/convex.config.js"
55
+ }
56
+ }
57
+ },
58
+ "peerDependencies": {
59
+ "convex": "^1.16.4"
60
+ },
61
+ "devDependencies": {
62
+ "@eslint/js": "^9.9.1",
63
+ "@types/node": "^18.17.0",
64
+ "eslint": "^9.9.1",
65
+ "convex-test": "^0.0.31",
66
+ "@fast-check/vitest": "^0.1.3",
67
+ "globals": "^15.9.0",
68
+ "vitest": "^2.1.1",
69
+ "prettier": "3.2.5",
70
+ "typescript": "~5.0.3",
71
+ "typescript-eslint": "^8.4.0"
72
+ },
73
+ "main": "./dist/commonjs/client/index.js",
74
+ "types": "./dist/commonjs/client/index.d.ts",
75
+ "module": "./dist/esm/client/index.js"
76
+ }
@@ -0,0 +1,82 @@
1
+ import {
2
+ Expand,
3
+ FunctionReference,
4
+ GenericDataModel,
5
+ GenericMutationCtx,
6
+ GenericQueryCtx,
7
+ } from "convex/server";
8
+ import { GenericId } from "convex/values";
9
+ import { api } from "../component/_generated/api";
10
+
11
+ export class ShardedCounter<Shards extends Record<string, number>> {
12
+ constructor(
13
+ public component: UseApi<typeof api>,
14
+ public options?: { shards?: Shards; defaultShards?: number }
15
+ ) {}
16
+ async add<Name extends string = keyof Shards & string>(
17
+ ctx: RunMutationCtx,
18
+ name: Name,
19
+ count: number = 1
20
+ ) {
21
+ const shards = this.options?.shards?.[name] ?? this.options?.defaultShards;
22
+ return ctx.runMutation(this.component.public.add, {
23
+ name,
24
+ count,
25
+ shards,
26
+ });
27
+ }
28
+ async count<Name extends string = keyof Shards & string>(
29
+ ctx: RunQueryCtx,
30
+ name: Name
31
+ ) {
32
+ return ctx.runQuery(this.component.public.count, { name });
33
+ }
34
+ // Another way of exporting functionality
35
+ for<Name extends string = keyof Shards & string>(name: Name) {
36
+ return {
37
+ add: async (ctx: RunMutationCtx, count: number = 1) =>
38
+ this.add(ctx, name, count),
39
+ subtract: async (ctx: RunMutationCtx, count: number = 1) =>
40
+ this.add(ctx, name, -count),
41
+ inc: async (ctx: RunMutationCtx) => this.add(ctx, name, 1),
42
+ dec: async (ctx: RunMutationCtx) => this.add(ctx, name, -1),
43
+ count: async (ctx: RunQueryCtx) => this.count(ctx, name),
44
+ };
45
+ }
46
+ }
47
+
48
+ /* Type utils follow */
49
+
50
+ type RunQueryCtx = {
51
+ runQuery: GenericQueryCtx<GenericDataModel>["runQuery"];
52
+ };
53
+ type RunMutationCtx = {
54
+ runMutation: GenericMutationCtx<GenericDataModel>["runMutation"];
55
+ };
56
+
57
+ export type OpaqueIds<T> =
58
+ T extends GenericId<infer _T>
59
+ ? string
60
+ : T extends (infer U)[]
61
+ ? OpaqueIds<U>[]
62
+ : T extends object
63
+ ? { [K in keyof T]: OpaqueIds<T[K]> }
64
+ : T;
65
+
66
+ export type UseApi<API> = Expand<{
67
+ [mod in keyof API]: API[mod] extends FunctionReference<
68
+ infer FType,
69
+ "public",
70
+ infer FArgs,
71
+ infer FReturnType,
72
+ infer FComponentPath
73
+ >
74
+ ? FunctionReference<
75
+ FType,
76
+ "internal",
77
+ OpaqueIds<FArgs>,
78
+ OpaqueIds<FReturnType>,
79
+ FComponentPath
80
+ >
81
+ : UseApi<API[mod]>;
82
+ }>;
@@ -0,0 +1,58 @@
1
+ /* prettier-ignore-start */
2
+
3
+ /* eslint-disable */
4
+ /**
5
+ * Generated `api` utility.
6
+ *
7
+ * THIS CODE IS AUTOMATICALLY GENERATED.
8
+ *
9
+ * To regenerate, run `npx convex dev`.
10
+ * @module
11
+ */
12
+
13
+ import type * as public from "../public.js";
14
+
15
+ import type {
16
+ ApiFromModules,
17
+ FilterApi,
18
+ FunctionReference,
19
+ } from "convex/server";
20
+ /**
21
+ * A utility for referencing Convex functions in your app's API.
22
+ *
23
+ * Usage:
24
+ * ```js
25
+ * const myFunctionReference = api.myModule.myFunction;
26
+ * ```
27
+ */
28
+ declare const fullApi: ApiFromModules<{
29
+ public: typeof public;
30
+ }>;
31
+ export type Mounts = {
32
+ public: {
33
+ add: FunctionReference<
34
+ "mutation",
35
+ "public",
36
+ { count: number; name: string; shards?: number },
37
+ null
38
+ >;
39
+ count: FunctionReference<"query", "public", { name: string }, number>;
40
+ };
41
+ };
42
+ // For now fullApiWithMounts is only fullApi which provides
43
+ // jump-to-definition in component client code.
44
+ // Use Mounts for the same type without the inference.
45
+ declare const fullApiWithMounts: typeof fullApi;
46
+
47
+ export declare const api: FilterApi<
48
+ typeof fullApiWithMounts,
49
+ FunctionReference<any, "public">
50
+ >;
51
+ export declare const internal: FilterApi<
52
+ typeof fullApiWithMounts,
53
+ FunctionReference<any, "internal">
54
+ >;
55
+
56
+ export declare const components: {};
57
+
58
+ /* prettier-ignore-end */
@@ -0,0 +1,27 @@
1
+ /* prettier-ignore-start */
2
+
3
+ /* eslint-disable */
4
+ /**
5
+ * Generated `api` utility.
6
+ *
7
+ * THIS CODE IS AUTOMATICALLY GENERATED.
8
+ *
9
+ * To regenerate, run `npx convex dev`.
10
+ * @module
11
+ */
12
+
13
+ import { anyApi, componentsGeneric } from "convex/server";
14
+
15
+ /**
16
+ * A utility for referencing Convex functions in your app's API.
17
+ *
18
+ * Usage:
19
+ * ```js
20
+ * const myFunctionReference = api.myModule.myFunction;
21
+ * ```
22
+ */
23
+ export const api = anyApi;
24
+ export const internal = anyApi;
25
+ export const components = componentsGeneric();
26
+
27
+ /* prettier-ignore-end */
@@ -0,0 +1,64 @@
1
+ /* prettier-ignore-start */
2
+
3
+ /* eslint-disable */
4
+ /**
5
+ * Generated data model types.
6
+ *
7
+ * THIS CODE IS AUTOMATICALLY GENERATED.
8
+ *
9
+ * To regenerate, run `npx convex dev`.
10
+ * @module
11
+ */
12
+
13
+ import type {
14
+ DataModelFromSchemaDefinition,
15
+ DocumentByName,
16
+ TableNamesInDataModel,
17
+ SystemTableNames,
18
+ } from "convex/server";
19
+ import type { GenericId } from "convex/values";
20
+ import schema from "../schema.js";
21
+
22
+ /**
23
+ * The names of all of your Convex tables.
24
+ */
25
+ export type TableNames = TableNamesInDataModel<DataModel>;
26
+
27
+ /**
28
+ * The type of a document stored in Convex.
29
+ *
30
+ * @typeParam TableName - A string literal type of the table name (like "users").
31
+ */
32
+ export type Doc<TableName extends TableNames> = DocumentByName<
33
+ DataModel,
34
+ TableName
35
+ >;
36
+
37
+ /**
38
+ * An identifier for a document in Convex.
39
+ *
40
+ * Convex documents are uniquely identified by their `Id`, which is accessible
41
+ * on the `_id` field. To learn more, see [Document IDs](https://docs.convex.dev/using/document-ids).
42
+ *
43
+ * Documents can be loaded using `db.get(id)` in query and mutation functions.
44
+ *
45
+ * IDs are just strings at runtime, but this type can be used to distinguish them from other
46
+ * strings when type checking.
47
+ *
48
+ * @typeParam TableName - A string literal type of the table name (like "users").
49
+ */
50
+ export type Id<TableName extends TableNames | SystemTableNames> =
51
+ GenericId<TableName>;
52
+
53
+ /**
54
+ * A type describing your Convex data model.
55
+ *
56
+ * This type includes information about what tables you have, the type of
57
+ * documents stored in those tables, and the indexes defined on them.
58
+ *
59
+ * This type is used to parameterize methods like `queryGeneric` and
60
+ * `mutationGeneric` to make them type-safe.
61
+ */
62
+ export type DataModel = DataModelFromSchemaDefinition<typeof schema>;
63
+
64
+ /* prettier-ignore-end */
@@ -0,0 +1,153 @@
1
+ /* prettier-ignore-start */
2
+
3
+ /* eslint-disable */
4
+ /**
5
+ * Generated utilities for implementing server-side Convex query and mutation functions.
6
+ *
7
+ * THIS CODE IS AUTOMATICALLY GENERATED.
8
+ *
9
+ * To regenerate, run `npx convex dev`.
10
+ * @module
11
+ */
12
+
13
+ import {
14
+ ActionBuilder,
15
+ AnyComponents,
16
+ HttpActionBuilder,
17
+ MutationBuilder,
18
+ QueryBuilder,
19
+ GenericActionCtx,
20
+ GenericMutationCtx,
21
+ GenericQueryCtx,
22
+ GenericDatabaseReader,
23
+ GenericDatabaseWriter,
24
+ FunctionReference,
25
+ } from "convex/server";
26
+ import type { DataModel } from "./dataModel.js";
27
+
28
+ type GenericCtx =
29
+ | GenericActionCtx<DataModel>
30
+ | GenericMutationCtx<DataModel>
31
+ | GenericQueryCtx<DataModel>;
32
+
33
+ /**
34
+ * Define a query in this Convex app's public API.
35
+ *
36
+ * This function will be allowed to read your Convex database and will be accessible from the client.
37
+ *
38
+ * @param func - The query function. It receives a {@link QueryCtx} as its first argument.
39
+ * @returns The wrapped query. Include this as an `export` to name it and make it accessible.
40
+ */
41
+ export declare const query: QueryBuilder<DataModel, "public">;
42
+
43
+ /**
44
+ * Define a query that is only accessible from other Convex functions (but not from the client).
45
+ *
46
+ * This function will be allowed to read from your Convex database. It will not be accessible from the client.
47
+ *
48
+ * @param func - The query function. It receives a {@link QueryCtx} as its first argument.
49
+ * @returns The wrapped query. Include this as an `export` to name it and make it accessible.
50
+ */
51
+ export declare const internalQuery: QueryBuilder<DataModel, "internal">;
52
+
53
+ /**
54
+ * Define a mutation in this Convex app's public API.
55
+ *
56
+ * This function will be allowed to modify your Convex database and will be accessible from the client.
57
+ *
58
+ * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
59
+ * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
60
+ */
61
+ export declare const mutation: MutationBuilder<DataModel, "public">;
62
+
63
+ /**
64
+ * Define a mutation that is only accessible from other Convex functions (but not from the client).
65
+ *
66
+ * This function will be allowed to modify your Convex database. It will not be accessible from the client.
67
+ *
68
+ * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
69
+ * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
70
+ */
71
+ export declare const internalMutation: MutationBuilder<DataModel, "internal">;
72
+
73
+ /**
74
+ * Define an action in this Convex app's public API.
75
+ *
76
+ * An action is a function which can execute any JavaScript code, including non-deterministic
77
+ * code and code with side-effects, like calling third-party services.
78
+ * They can be run in Convex's JavaScript environment or in Node.js using the "use node" directive.
79
+ * They can interact with the database indirectly by calling queries and mutations using the {@link ActionCtx}.
80
+ *
81
+ * @param func - The action. It receives an {@link ActionCtx} as its first argument.
82
+ * @returns The wrapped action. Include this as an `export` to name it and make it accessible.
83
+ */
84
+ export declare const action: ActionBuilder<DataModel, "public">;
85
+
86
+ /**
87
+ * Define an action that is only accessible from other Convex functions (but not from the client).
88
+ *
89
+ * @param func - The function. It receives an {@link ActionCtx} as its first argument.
90
+ * @returns The wrapped function. Include this as an `export` to name it and make it accessible.
91
+ */
92
+ export declare const internalAction: ActionBuilder<DataModel, "internal">;
93
+
94
+ /**
95
+ * Define an HTTP action.
96
+ *
97
+ * This function will be used to respond to HTTP requests received by a Convex
98
+ * deployment if the requests matches the path and method where this action
99
+ * is routed. Be sure to route your action in `convex/http.js`.
100
+ *
101
+ * @param func - The function. It receives an {@link ActionCtx} as its first argument.
102
+ * @returns The wrapped function. Import this function from `convex/http.js` and route it to hook it up.
103
+ */
104
+ export declare const httpAction: HttpActionBuilder;
105
+
106
+ /**
107
+ * A set of services for use within Convex query functions.
108
+ *
109
+ * The query context is passed as the first argument to any Convex query
110
+ * function run on the server.
111
+ *
112
+ * This differs from the {@link MutationCtx} because all of the services are
113
+ * read-only.
114
+ */
115
+ export type QueryCtx = GenericQueryCtx<DataModel>;
116
+
117
+ /**
118
+ * A set of services for use within Convex mutation functions.
119
+ *
120
+ * The mutation context is passed as the first argument to any Convex mutation
121
+ * function run on the server.
122
+ */
123
+ export type MutationCtx = GenericMutationCtx<DataModel>;
124
+
125
+ /**
126
+ * A set of services for use within Convex action functions.
127
+ *
128
+ * The action context is passed as the first argument to any Convex action
129
+ * function run on the server.
130
+ */
131
+ export type ActionCtx = GenericActionCtx<DataModel>;
132
+
133
+ /**
134
+ * An interface to read from the database within Convex query functions.
135
+ *
136
+ * The two entry points are {@link DatabaseReader.get}, which fetches a single
137
+ * document by its {@link Id}, or {@link DatabaseReader.query}, which starts
138
+ * building a query.
139
+ */
140
+ export type DatabaseReader = GenericDatabaseReader<DataModel>;
141
+
142
+ /**
143
+ * An interface to read from and write to the database within Convex mutation
144
+ * functions.
145
+ *
146
+ * Convex guarantees that all writes within a single mutation are
147
+ * executed atomically, so you never have to worry about partial writes leaving
148
+ * your data in an inconsistent state. See [the Convex Guide](https://docs.convex.dev/understanding/convex-fundamentals/functions#atomicity-and-optimistic-concurrency-control)
149
+ * for the guarantees Convex provides your functions.
150
+ */
151
+ export type DatabaseWriter = GenericDatabaseWriter<DataModel>;
152
+
153
+ /* prettier-ignore-end */
@@ -0,0 +1,94 @@
1
+ /* prettier-ignore-start */
2
+
3
+ /* eslint-disable */
4
+ /**
5
+ * Generated utilities for implementing server-side Convex query and mutation functions.
6
+ *
7
+ * THIS CODE IS AUTOMATICALLY GENERATED.
8
+ *
9
+ * To regenerate, run `npx convex dev`.
10
+ * @module
11
+ */
12
+
13
+ import {
14
+ actionGeneric,
15
+ httpActionGeneric,
16
+ queryGeneric,
17
+ mutationGeneric,
18
+ internalActionGeneric,
19
+ internalMutationGeneric,
20
+ internalQueryGeneric,
21
+ componentsGeneric,
22
+ } from "convex/server";
23
+
24
+ /**
25
+ * Define a query in this Convex app's public API.
26
+ *
27
+ * This function will be allowed to read your Convex database and will be accessible from the client.
28
+ *
29
+ * @param func - The query function. It receives a {@link QueryCtx} as its first argument.
30
+ * @returns The wrapped query. Include this as an `export` to name it and make it accessible.
31
+ */
32
+ export const query = queryGeneric;
33
+
34
+ /**
35
+ * Define a query that is only accessible from other Convex functions (but not from the client).
36
+ *
37
+ * This function will be allowed to read from your Convex database. It will not be accessible from the client.
38
+ *
39
+ * @param func - The query function. It receives a {@link QueryCtx} as its first argument.
40
+ * @returns The wrapped query. Include this as an `export` to name it and make it accessible.
41
+ */
42
+ export const internalQuery = internalQueryGeneric;
43
+
44
+ /**
45
+ * Define a mutation in this Convex app's public API.
46
+ *
47
+ * This function will be allowed to modify your Convex database and will be accessible from the client.
48
+ *
49
+ * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
50
+ * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
51
+ */
52
+ export const mutation = mutationGeneric;
53
+
54
+ /**
55
+ * Define a mutation that is only accessible from other Convex functions (but not from the client).
56
+ *
57
+ * This function will be allowed to modify your Convex database. It will not be accessible from the client.
58
+ *
59
+ * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
60
+ * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
61
+ */
62
+ export const internalMutation = internalMutationGeneric;
63
+
64
+ /**
65
+ * Define an action in this Convex app's public API.
66
+ *
67
+ * An action is a function which can execute any JavaScript code, including non-deterministic
68
+ * code and code with side-effects, like calling third-party services.
69
+ * They can be run in Convex's JavaScript environment or in Node.js using the "use node" directive.
70
+ * They can interact with the database indirectly by calling queries and mutations using the {@link ActionCtx}.
71
+ *
72
+ * @param func - The action. It receives an {@link ActionCtx} as its first argument.
73
+ * @returns The wrapped action. Include this as an `export` to name it and make it accessible.
74
+ */
75
+ export const action = actionGeneric;
76
+
77
+ /**
78
+ * Define an action that is only accessible from other Convex functions (but not from the client).
79
+ *
80
+ * @param func - The function. It receives an {@link ActionCtx} as its first argument.
81
+ * @returns The wrapped function. Include this as an `export` to name it and make it accessible.
82
+ */
83
+ export const internalAction = internalActionGeneric;
84
+
85
+ /**
86
+ * Define a Convex HTTP action.
87
+ *
88
+ * @param func - The function. It receives an {@link ActionCtx} as its first argument, and a `Request` object
89
+ * as its second.
90
+ * @returns The wrapped endpoint function. Route a URL path to this function in `convex/http.js`.
91
+ */
92
+ export const httpAction = httpActionGeneric;
93
+
94
+ /* prettier-ignore-end */
@@ -0,0 +1,3 @@
1
+ import { defineComponent } from "convex/server";
2
+
3
+ export default defineComponent("shardedCounter");
@@ -0,0 +1,45 @@
1
+ /// <reference types="vite/client" />
2
+
3
+ import { describe, expect, test } from "vitest";
4
+ import { convexTest } from "convex-test";
5
+ import schema from "./schema.js";
6
+ import { test as fcTest, fc } from "@fast-check/vitest";
7
+ import { api } from "./_generated/api.js";
8
+
9
+ const modules = import.meta.glob("./**/*.*s");
10
+
11
+ describe("counter", () => {
12
+ test("add and subtract", async () => {
13
+ const t = convexTest(schema, modules);
14
+ await t.mutation(api.public.add, { name: "beans", count: 10 });
15
+ await t.mutation(api.public.add, { name: "beans", count: 5 });
16
+ expect(await t.query(api.public.count, { name: "beans" })).toEqual(15);
17
+ await t.mutation(api.public.add, { name: "beans", count: -5 });
18
+ expect(await t.query(api.public.count, { name: "friends" })).toEqual(0);
19
+ await t.mutation(api.public.add, { name: "friends", count: 6, shards: 1 });
20
+ await t.mutation(api.public.add, { name: "friends", count: 2, shards: 1 });
21
+ await t.mutation(api.public.add, { name: "friends", count: 3, shards: 3 });
22
+ expect(await t.query(api.public.count, { name: "beans" })).toEqual(10);
23
+ expect(await t.query(api.public.count, { name: "friends" })).toEqual(11);
24
+ });
25
+ });
26
+
27
+ fcTest.prop({
28
+ updates: fc.array(fc.record({
29
+ v: fc.integer({ min: 0, max: 10000 }).map((i) => i / 100),
30
+ key: fc.string(),
31
+ shards: fc.option(fc.integer({ min: 1, max: 100 })),
32
+ })),
33
+ })(
34
+ "updates to counter should match in-memory counter which ignores sharding",
35
+ async ({ updates }) => {
36
+ const t = convexTest(schema, modules);
37
+ const counter = new Map<string, number>();
38
+ for (const { v, key, shards } of updates) {
39
+ counter.set(key, (counter.get(key) ?? 0) + v);
40
+ await t.mutation(api.public.add, { name: key, count: v, shards: shards ?? undefined });
41
+ const count = await t.query(api.public.count, { name: key });
42
+ expect(count).toBeCloseTo(counter.get(key)!);
43
+ }
44
+ },
45
+ );
@@ -0,0 +1,43 @@
1
+ import { v } from "convex/values";
2
+ import { mutation, query } from "./_generated/server";
3
+
4
+ export const DEFAULT_SHARD_COUNT = 16;
5
+
6
+ export const add = mutation({
7
+ args: {
8
+ name: v.string(),
9
+ count: v.number(),
10
+ shards: v.optional(v.number()),
11
+ },
12
+ returns: v.null(),
13
+ handler: async (ctx, args) => {
14
+ const shard = Math.floor(Math.random() * (args.shards ?? DEFAULT_SHARD_COUNT));
15
+ const counter = await ctx.db
16
+ .query("counters")
17
+ .withIndex("name", (q) => q.eq("name", args.name).eq("shard", shard))
18
+ .unique();
19
+ if (counter) {
20
+ await ctx.db.patch(counter._id, {
21
+ value: counter.value + args.count,
22
+ });
23
+ } else {
24
+ await ctx.db.insert("counters", {
25
+ name: args.name,
26
+ value: args.count,
27
+ shard,
28
+ });
29
+ }
30
+ },
31
+ });
32
+
33
+ export const count = query({
34
+ args: { name: v.string() },
35
+ returns: v.number(),
36
+ handler: async (ctx, args) => {
37
+ const counters = await ctx.db
38
+ .query("counters")
39
+ .withIndex("name", (q) => q.eq("name", args.name))
40
+ .collect();
41
+ return counters.reduce((sum, counter) => sum + counter.value, 0);
42
+ },
43
+ });
@@ -0,0 +1,10 @@
1
+ import { defineSchema, defineTable } from "convex/server";
2
+ import { v } from "convex/values";
3
+
4
+ export default defineSchema({
5
+ counters: defineTable({
6
+ name: v.string(),
7
+ value: v.number(),
8
+ shard: v.number(),
9
+ }).index("name", ["name", "shard"]),
10
+ });