@fatagnus/remote-cmd-relay-convex 1.0.0

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.
@@ -0,0 +1,161 @@
1
+ /* eslint-disable */
2
+ /**
3
+ * Generated utilities for implementing server-side Convex query and mutation functions.
4
+ *
5
+ * THIS CODE IS AUTOMATICALLY GENERATED.
6
+ *
7
+ * To regenerate, run `npx convex dev`.
8
+ * @module
9
+ */
10
+
11
+ import type {
12
+ ActionBuilder,
13
+ HttpActionBuilder,
14
+ MutationBuilder,
15
+ QueryBuilder,
16
+ GenericActionCtx,
17
+ GenericMutationCtx,
18
+ GenericQueryCtx,
19
+ GenericDatabaseReader,
20
+ GenericDatabaseWriter,
21
+ } from "convex/server";
22
+ import {
23
+ actionGeneric,
24
+ httpActionGeneric,
25
+ queryGeneric,
26
+ mutationGeneric,
27
+ internalActionGeneric,
28
+ internalMutationGeneric,
29
+ internalQueryGeneric,
30
+ } from "convex/server";
31
+ import type { DataModel } from "./dataModel.js";
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 const query: QueryBuilder<DataModel, "public"> = queryGeneric;
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 const internalQuery: QueryBuilder<DataModel, "internal"> =
52
+ internalQueryGeneric;
53
+
54
+ /**
55
+ * Define a mutation in this Convex app's public API.
56
+ *
57
+ * This function will be allowed to modify your Convex database and will 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 mutation: MutationBuilder<DataModel, "public"> = mutationGeneric;
63
+
64
+ /**
65
+ * Define a mutation that is only accessible from other Convex functions (but not from the client).
66
+ *
67
+ * This function will be allowed to modify your Convex database. It will not be accessible from the client.
68
+ *
69
+ * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
70
+ * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
71
+ */
72
+ export const internalMutation: MutationBuilder<DataModel, "internal"> =
73
+ internalMutationGeneric;
74
+
75
+ /**
76
+ * Define an action in this Convex app's public API.
77
+ *
78
+ * An action is a function which can execute any JavaScript code, including non-deterministic
79
+ * code and code with side-effects, like calling third-party services.
80
+ * They can be run in Convex's JavaScript environment or in Node.js using the "use node" directive.
81
+ * They can interact with the database indirectly by calling queries and mutations using the {@link ActionCtx}.
82
+ *
83
+ * @param func - The action. It receives an {@link ActionCtx} as its first argument.
84
+ * @returns The wrapped action. Include this as an `export` to name it and make it accessible.
85
+ */
86
+ export const action: ActionBuilder<DataModel, "public"> = actionGeneric;
87
+
88
+ /**
89
+ * Define an action that is only accessible from other Convex functions (but not from the client).
90
+ *
91
+ * @param func - The function. It receives an {@link ActionCtx} as its first argument.
92
+ * @returns The wrapped function. Include this as an `export` to name it and make it accessible.
93
+ */
94
+ export const internalAction: ActionBuilder<DataModel, "internal"> =
95
+ internalActionGeneric;
96
+
97
+ /**
98
+ * Define an HTTP action.
99
+ *
100
+ * The wrapped function will be used to respond to HTTP requests received
101
+ * by a Convex deployment if the requests matches the path and method where
102
+ * this action is routed. Be sure to route your httpAction in `convex/http.js`.
103
+ *
104
+ * @param func - The function. It receives an {@link ActionCtx} as its first argument
105
+ * and a Fetch API `Request` object as its second.
106
+ * @returns The wrapped function. Import this function from `convex/http.js` and route it to hook it up.
107
+ */
108
+ export const httpAction: HttpActionBuilder = httpActionGeneric;
109
+
110
+ type GenericCtx =
111
+ | GenericActionCtx<DataModel>
112
+ | GenericMutationCtx<DataModel>
113
+ | GenericQueryCtx<DataModel>;
114
+
115
+ /**
116
+ * A set of services for use within Convex query functions.
117
+ *
118
+ * The query context is passed as the first argument to any Convex query
119
+ * function run on the server.
120
+ *
121
+ * If you're using code generation, use the `QueryCtx` type in `convex/_generated/server.d.ts` instead.
122
+ */
123
+ export type QueryCtx = GenericQueryCtx<DataModel>;
124
+
125
+ /**
126
+ * A set of services for use within Convex mutation functions.
127
+ *
128
+ * The mutation context is passed as the first argument to any Convex mutation
129
+ * function run on the server.
130
+ *
131
+ * If you're using code generation, use the `MutationCtx` type in `convex/_generated/server.d.ts` instead.
132
+ */
133
+ export type MutationCtx = GenericMutationCtx<DataModel>;
134
+
135
+ /**
136
+ * A set of services for use within Convex action functions.
137
+ *
138
+ * The action context is passed as the first argument to any Convex action
139
+ * function run on the server.
140
+ */
141
+ export type ActionCtx = GenericActionCtx<DataModel>;
142
+
143
+ /**
144
+ * An interface to read from the database within Convex query functions.
145
+ *
146
+ * The two entry points are {@link DatabaseReader.get}, which fetches a single
147
+ * document by its {@link Id}, or {@link DatabaseReader.query}, which starts
148
+ * building a query.
149
+ */
150
+ export type DatabaseReader = GenericDatabaseReader<DataModel>;
151
+
152
+ /**
153
+ * An interface to read from and write to the database within Convex mutation
154
+ * functions.
155
+ *
156
+ * Convex guarantees that all writes within a single mutation are
157
+ * executed atomically, so you never have to worry about partial writes leaving
158
+ * your data in an inconsistent state. See [the Convex Guide](https://docs.convex.dev/understanding/convex-fundamentals/functions#atomicity-and-optimistic-concurrency-control)
159
+ * for the guarantees Convex provides your functions.
160
+ */
161
+ export type DatabaseWriter = GenericDatabaseWriter<DataModel>;
@@ -0,0 +1,233 @@
1
+ import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
2
+ import {
3
+ createRelayTestConvex,
4
+ createTestRelayAssignment,
5
+ type RelayTestConvex,
6
+ } from "./test.setup";
7
+ import { api } from "./_generated/api";
8
+
9
+ describe("relay assignments", () => {
10
+ let t: RelayTestConvex;
11
+
12
+ beforeEach(() => {
13
+ vi.useFakeTimers();
14
+ t = createRelayTestConvex();
15
+ });
16
+
17
+ afterEach(async () => {
18
+ await t.finishAllScheduledFunctions(vi.runAllTimers);
19
+ vi.useRealTimers();
20
+ });
21
+
22
+ describe("create", () => {
23
+ it("creates a relay assignment", async () => {
24
+ const result = await t.mutation(api.assignments.create, {
25
+ apiKeyId: "api-key-123",
26
+ machineId: "machine-456",
27
+ name: "Test Relay",
28
+ createdBy: "user-789",
29
+ });
30
+
31
+ expect(result).toBeDefined();
32
+
33
+ // Verify the assignment was created
34
+ const assignment = await t.run(async (ctx) => {
35
+ return await ctx.db.get(result);
36
+ });
37
+
38
+ expect(assignment).not.toBeNull();
39
+ expect(assignment?.apiKeyId).toBe("api-key-123");
40
+ expect(assignment?.machineId).toBe("machine-456");
41
+ expect(assignment?.name).toBe("Test Relay");
42
+ expect(assignment?.enabled).toBe(true);
43
+ });
44
+
45
+ it("prevents duplicate API key assignments", async () => {
46
+ await t.mutation(api.assignments.create, {
47
+ apiKeyId: "api-key-duplicate",
48
+ machineId: "machine-1",
49
+ name: "First Relay",
50
+ createdBy: "user-1",
51
+ });
52
+
53
+ await expect(
54
+ t.mutation(api.assignments.create, {
55
+ apiKeyId: "api-key-duplicate",
56
+ machineId: "machine-2",
57
+ name: "Second Relay",
58
+ createdBy: "user-1",
59
+ })
60
+ ).rejects.toThrow("API key is already assigned to a machine");
61
+ });
62
+ });
63
+
64
+ describe("getByApiKeyId", () => {
65
+ it("returns assignment by API key ID", async () => {
66
+ const created = await createTestRelayAssignment(t, {
67
+ apiKeyId: "lookup-key",
68
+ name: "Lookup Relay",
69
+ });
70
+
71
+ const result = await t.query(api.assignments.getByApiKeyId, {
72
+ apiKeyId: "lookup-key",
73
+ });
74
+
75
+ expect(result).not.toBeNull();
76
+ expect(result?._id).toBe(created._id);
77
+ expect(result?.name).toBe("Lookup Relay");
78
+ });
79
+
80
+ it("returns null for unknown API key", async () => {
81
+ const result = await t.query(api.assignments.getByApiKeyId, {
82
+ apiKeyId: "unknown-key",
83
+ });
84
+
85
+ expect(result).toBeNull();
86
+ });
87
+ });
88
+
89
+ describe("listByMachineId", () => {
90
+ it("lists assignments for a machine", async () => {
91
+ await createTestRelayAssignment(t, {
92
+ machineId: "target-machine",
93
+ apiKeyId: "key-1",
94
+ name: "Relay 1",
95
+ });
96
+ await createTestRelayAssignment(t, {
97
+ machineId: "target-machine",
98
+ apiKeyId: "key-2",
99
+ name: "Relay 2",
100
+ });
101
+ await createTestRelayAssignment(t, {
102
+ machineId: "other-machine",
103
+ apiKeyId: "key-3",
104
+ name: "Other Relay",
105
+ });
106
+
107
+ const result = await t.query(api.assignments.listByMachineId, {
108
+ machineId: "target-machine",
109
+ });
110
+
111
+ expect(result).toHaveLength(2);
112
+ expect(result.map((r) => r.name).sort()).toEqual(["Relay 1", "Relay 2"]);
113
+ });
114
+
115
+ it("returns empty array for machine with no assignments", async () => {
116
+ const result = await t.query(api.assignments.listByMachineId, {
117
+ machineId: "no-assignments-machine",
118
+ });
119
+
120
+ expect(result).toHaveLength(0);
121
+ });
122
+ });
123
+
124
+ describe("listAll", () => {
125
+ it("lists all assignments", async () => {
126
+ await createTestRelayAssignment(t, { apiKeyId: "key-a", name: "Relay A" });
127
+ await createTestRelayAssignment(t, { apiKeyId: "key-b", name: "Relay B" });
128
+
129
+ const result = await t.query(api.assignments.listAll, {});
130
+
131
+ expect(result).toHaveLength(2);
132
+ });
133
+ });
134
+
135
+ describe("update", () => {
136
+ it("updates assignment name", async () => {
137
+ const created = await createTestRelayAssignment(t, {
138
+ name: "Original Name",
139
+ });
140
+
141
+ await t.mutation(api.assignments.update, {
142
+ id: created._id,
143
+ name: "Updated Name",
144
+ });
145
+
146
+ const updated = await t.run(async (ctx) => {
147
+ return await ctx.db.get(created._id);
148
+ });
149
+
150
+ expect(updated?.name).toBe("Updated Name");
151
+ });
152
+
153
+ it("updates assignment enabled status", async () => {
154
+ const created = await createTestRelayAssignment(t, {
155
+ enabled: true,
156
+ });
157
+
158
+ await t.mutation(api.assignments.update, {
159
+ id: created._id,
160
+ enabled: false,
161
+ });
162
+
163
+ const updated = await t.run(async (ctx) => {
164
+ return await ctx.db.get(created._id);
165
+ });
166
+
167
+ expect(updated?.enabled).toBe(false);
168
+ });
169
+
170
+ it("throws for non-existent assignment", async () => {
171
+ // Create and delete an assignment to get a valid but non-existent ID
172
+ const created = await createTestRelayAssignment(t);
173
+ await t.run(async (ctx) => {
174
+ await ctx.db.delete(created._id);
175
+ });
176
+
177
+ await expect(
178
+ t.mutation(api.assignments.update, {
179
+ id: created._id,
180
+ name: "Will Fail",
181
+ })
182
+ ).rejects.toThrow("Relay assignment not found");
183
+ });
184
+ });
185
+
186
+ describe("heartbeat", () => {
187
+ it("updates lastSeenAt timestamp", async () => {
188
+ const created = await createTestRelayAssignment(t, {
189
+ apiKeyId: "heartbeat-key",
190
+ });
191
+
192
+ // Verify no lastSeenAt initially
193
+ const before = await t.run(async (ctx) => {
194
+ return await ctx.db.get(created._id);
195
+ });
196
+ expect(before?.lastSeenAt).toBeUndefined();
197
+
198
+ // Send heartbeat
199
+ await t.mutation(api.assignments.heartbeat, {
200
+ apiKeyId: "heartbeat-key",
201
+ });
202
+
203
+ const after = await t.run(async (ctx) => {
204
+ return await ctx.db.get(created._id);
205
+ });
206
+
207
+ expect(after?.lastSeenAt).toBeDefined();
208
+ });
209
+
210
+ it("does nothing for unknown API key", async () => {
211
+ // Should not throw
212
+ await t.mutation(api.assignments.heartbeat, {
213
+ apiKeyId: "unknown-heartbeat-key",
214
+ });
215
+ });
216
+ });
217
+
218
+ describe("remove", () => {
219
+ it("deletes an assignment", async () => {
220
+ const created = await createTestRelayAssignment(t);
221
+
222
+ await t.mutation(api.assignments.remove, {
223
+ id: created._id,
224
+ });
225
+
226
+ const deleted = await t.run(async (ctx) => {
227
+ return await ctx.db.get(created._id);
228
+ });
229
+
230
+ expect(deleted).toBeNull();
231
+ });
232
+ });
233
+ });
@@ -0,0 +1,222 @@
1
+ import { v } from "convex/values";
2
+ import { mutation, query } from "./_generated/server";
3
+
4
+ /**
5
+ * Create a new relay assignment linking an API key to a machine
6
+ */
7
+ export const create = mutation({
8
+ args: {
9
+ apiKeyId: v.string(),
10
+ machineId: v.string(),
11
+ name: v.string(),
12
+ createdBy: v.string(),
13
+ },
14
+ returns: v.id("relayAssignments"),
15
+ handler: async (ctx, args) => {
16
+ const now = Date.now();
17
+
18
+ // Check if assignment already exists for this API key
19
+ const existing = await ctx.db
20
+ .query("relayAssignments")
21
+ .withIndex("by_apiKeyId", (q) => q.eq("apiKeyId", args.apiKeyId))
22
+ .first();
23
+
24
+ if (existing) {
25
+ throw new Error("API key is already assigned to a machine");
26
+ }
27
+
28
+ return await ctx.db.insert("relayAssignments", {
29
+ apiKeyId: args.apiKeyId,
30
+ machineId: args.machineId,
31
+ name: args.name,
32
+ enabled: true,
33
+ createdBy: args.createdBy,
34
+ createdAt: now,
35
+ updatedAt: now,
36
+ });
37
+ },
38
+ });
39
+
40
+ /**
41
+ * Get a relay assignment by API key ID
42
+ */
43
+ export const getByApiKeyId = query({
44
+ args: {
45
+ apiKeyId: v.string(),
46
+ },
47
+ returns: v.union(
48
+ v.object({
49
+ _id: v.id("relayAssignments"),
50
+ apiKeyId: v.string(),
51
+ machineId: v.string(),
52
+ name: v.string(),
53
+ enabled: v.boolean(),
54
+ lastSeenAt: v.optional(v.number()),
55
+ createdBy: v.string(),
56
+ createdAt: v.number(),
57
+ updatedAt: v.number(),
58
+ }),
59
+ v.null()
60
+ ),
61
+ handler: async (ctx, args) => {
62
+ const assignment = await ctx.db
63
+ .query("relayAssignments")
64
+ .withIndex("by_apiKeyId", (q) => q.eq("apiKeyId", args.apiKeyId))
65
+ .first();
66
+
67
+ if (!assignment) return null;
68
+
69
+ return {
70
+ _id: assignment._id,
71
+ apiKeyId: assignment.apiKeyId,
72
+ machineId: assignment.machineId,
73
+ name: assignment.name,
74
+ enabled: assignment.enabled,
75
+ lastSeenAt: assignment.lastSeenAt,
76
+ createdBy: assignment.createdBy,
77
+ createdAt: assignment.createdAt,
78
+ updatedAt: assignment.updatedAt,
79
+ };
80
+ },
81
+ });
82
+
83
+ /**
84
+ * List all relay assignments for a machine
85
+ */
86
+ export const listByMachineId = query({
87
+ args: {
88
+ machineId: v.string(),
89
+ },
90
+ returns: v.array(
91
+ v.object({
92
+ _id: v.id("relayAssignments"),
93
+ apiKeyId: v.string(),
94
+ machineId: v.string(),
95
+ name: v.string(),
96
+ enabled: v.boolean(),
97
+ lastSeenAt: v.optional(v.number()),
98
+ createdBy: v.string(),
99
+ createdAt: v.number(),
100
+ updatedAt: v.number(),
101
+ })
102
+ ),
103
+ handler: async (ctx, args) => {
104
+ const assignments = await ctx.db
105
+ .query("relayAssignments")
106
+ .withIndex("by_machineId", (q) => q.eq("machineId", args.machineId))
107
+ .collect();
108
+
109
+ return assignments.map((a) => ({
110
+ _id: a._id,
111
+ apiKeyId: a.apiKeyId,
112
+ machineId: a.machineId,
113
+ name: a.name,
114
+ enabled: a.enabled,
115
+ lastSeenAt: a.lastSeenAt,
116
+ createdBy: a.createdBy,
117
+ createdAt: a.createdAt,
118
+ updatedAt: a.updatedAt,
119
+ }));
120
+ },
121
+ });
122
+
123
+ /**
124
+ * Update relay assignment
125
+ */
126
+ export const update = mutation({
127
+ args: {
128
+ id: v.id("relayAssignments"),
129
+ name: v.optional(v.string()),
130
+ enabled: v.optional(v.boolean()),
131
+ },
132
+ returns: v.null(),
133
+ handler: async (ctx, args) => {
134
+ const { id, ...updates } = args;
135
+ const existing = await ctx.db.get(id);
136
+ if (!existing) {
137
+ throw new Error("Relay assignment not found");
138
+ }
139
+
140
+ await ctx.db.patch(id, {
141
+ ...updates,
142
+ updatedAt: Date.now(),
143
+ });
144
+ return null;
145
+ },
146
+ });
147
+
148
+ /**
149
+ * Update last seen timestamp for a relay
150
+ */
151
+ export const heartbeat = mutation({
152
+ args: {
153
+ apiKeyId: v.string(),
154
+ },
155
+ returns: v.null(),
156
+ handler: async (ctx, args) => {
157
+ const assignment = await ctx.db
158
+ .query("relayAssignments")
159
+ .withIndex("by_apiKeyId", (q) => q.eq("apiKeyId", args.apiKeyId))
160
+ .first();
161
+
162
+ if (assignment) {
163
+ await ctx.db.patch(assignment._id, {
164
+ lastSeenAt: Date.now(),
165
+ updatedAt: Date.now(),
166
+ });
167
+ }
168
+ return null;
169
+ },
170
+ });
171
+
172
+ /**
173
+ * List all relay assignments (for admin view)
174
+ */
175
+ export const listAll = query({
176
+ args: {},
177
+ returns: v.array(
178
+ v.object({
179
+ _id: v.id("relayAssignments"),
180
+ apiKeyId: v.string(),
181
+ machineId: v.string(),
182
+ name: v.string(),
183
+ enabled: v.boolean(),
184
+ lastSeenAt: v.optional(v.number()),
185
+ createdBy: v.string(),
186
+ createdAt: v.number(),
187
+ updatedAt: v.number(),
188
+ })
189
+ ),
190
+ handler: async (ctx) => {
191
+ const assignments = await ctx.db
192
+ .query("relayAssignments")
193
+ .order("desc")
194
+ .collect();
195
+
196
+ return assignments.map((a) => ({
197
+ _id: a._id,
198
+ apiKeyId: a.apiKeyId,
199
+ machineId: a.machineId,
200
+ name: a.name,
201
+ enabled: a.enabled,
202
+ lastSeenAt: a.lastSeenAt,
203
+ createdBy: a.createdBy,
204
+ createdAt: a.createdAt,
205
+ updatedAt: a.updatedAt,
206
+ }));
207
+ },
208
+ });
209
+
210
+ /**
211
+ * Delete a relay assignment
212
+ */
213
+ export const remove = mutation({
214
+ args: {
215
+ id: v.id("relayAssignments"),
216
+ },
217
+ returns: v.null(),
218
+ handler: async (ctx, args) => {
219
+ await ctx.db.delete(args.id);
220
+ return null;
221
+ },
222
+ });