@synnaxlabs/client 0.40.0 → 0.42.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.
Files changed (142) hide show
  1. package/.turbo/turbo-build.log +7 -7
  2. package/dist/access/payload.d.ts +7 -1
  3. package/dist/access/payload.d.ts.map +1 -1
  4. package/dist/access/policy/payload.d.ts +182 -142
  5. package/dist/access/policy/payload.d.ts.map +1 -1
  6. package/dist/access/policy/retriever.d.ts +25 -22
  7. package/dist/access/policy/retriever.d.ts.map +1 -1
  8. package/dist/auth/auth.d.ts +1 -7
  9. package/dist/auth/auth.d.ts.map +1 -1
  10. package/dist/channel/client.d.ts +2 -7
  11. package/dist/channel/client.d.ts.map +1 -1
  12. package/dist/channel/payload.d.ts +13 -74
  13. package/dist/channel/payload.d.ts.map +1 -1
  14. package/dist/channel/retriever.d.ts +5 -31
  15. package/dist/channel/retriever.d.ts.map +1 -1
  16. package/dist/channel/writer.d.ts +6 -18
  17. package/dist/channel/writer.d.ts.map +1 -1
  18. package/dist/client.cjs +35 -30
  19. package/dist/client.d.ts +8 -56
  20. package/dist/client.d.ts.map +1 -1
  21. package/dist/client.js +6391 -3850
  22. package/dist/connection/checker.d.ts +22 -39
  23. package/dist/connection/checker.d.ts.map +1 -1
  24. package/dist/control/client.d.ts.map +1 -1
  25. package/dist/control/state.d.ts +6 -26
  26. package/dist/control/state.d.ts.map +1 -1
  27. package/dist/errors.d.ts +31 -56
  28. package/dist/errors.d.ts.map +1 -1
  29. package/dist/framer/adapter.d.ts +4 -0
  30. package/dist/framer/adapter.d.ts.map +1 -1
  31. package/dist/framer/client.d.ts +2 -2
  32. package/dist/framer/client.d.ts.map +1 -1
  33. package/dist/framer/codec.d.ts +34 -0
  34. package/dist/framer/codec.d.ts.map +1 -0
  35. package/dist/framer/codec.spec.d.ts +2 -0
  36. package/dist/framer/codec.spec.d.ts.map +1 -0
  37. package/dist/framer/deleter.d.ts +12 -49
  38. package/dist/framer/deleter.d.ts.map +1 -1
  39. package/dist/framer/frame.d.ts +26 -88
  40. package/dist/framer/frame.d.ts.map +1 -1
  41. package/dist/framer/iterator.d.ts.map +1 -1
  42. package/dist/framer/streamer.d.ts +69 -11
  43. package/dist/framer/streamer.d.ts.map +1 -1
  44. package/dist/framer/writer.d.ts +60 -257
  45. package/dist/framer/writer.d.ts.map +1 -1
  46. package/dist/hardware/device/client.d.ts +13 -24
  47. package/dist/hardware/device/client.d.ts.map +1 -1
  48. package/dist/hardware/device/payload.d.ts +25 -44
  49. package/dist/hardware/device/payload.d.ts.map +1 -1
  50. package/dist/hardware/rack/client.d.ts +12 -5
  51. package/dist/hardware/rack/client.d.ts.map +1 -1
  52. package/dist/hardware/rack/payload.d.ts +36 -15
  53. package/dist/hardware/rack/payload.d.ts.map +1 -1
  54. package/dist/hardware/task/client.d.ts +4 -20
  55. package/dist/hardware/task/client.d.ts.map +1 -1
  56. package/dist/hardware/task/payload.d.ts +41 -116
  57. package/dist/hardware/task/payload.d.ts.map +1 -1
  58. package/dist/index.d.ts +0 -2
  59. package/dist/index.d.ts.map +1 -1
  60. package/dist/label/payload.d.ts +1 -9
  61. package/dist/label/payload.d.ts.map +1 -1
  62. package/dist/label/writer.d.ts +27 -36
  63. package/dist/label/writer.d.ts.map +1 -1
  64. package/dist/ontology/client.d.ts +46 -36
  65. package/dist/ontology/client.d.ts.map +1 -1
  66. package/dist/ontology/group/payload.d.ts +1 -7
  67. package/dist/ontology/group/payload.d.ts.map +1 -1
  68. package/dist/ontology/payload.d.ts +239 -146
  69. package/dist/ontology/payload.d.ts.map +1 -1
  70. package/dist/ranger/client.d.ts +13 -55
  71. package/dist/ranger/client.d.ts.map +1 -1
  72. package/dist/ranger/kv.d.ts +7 -49
  73. package/dist/ranger/kv.d.ts.map +1 -1
  74. package/dist/ranger/payload.d.ts +21 -99
  75. package/dist/ranger/payload.d.ts.map +1 -1
  76. package/dist/ranger/writer.d.ts +35 -88
  77. package/dist/ranger/writer.d.ts.map +1 -1
  78. package/dist/testutil/indexedPair.d.ts +5 -0
  79. package/dist/testutil/indexedPair.d.ts.map +1 -0
  80. package/dist/testutil/telem.d.ts +3 -0
  81. package/dist/testutil/telem.d.ts.map +1 -0
  82. package/dist/transport.d.ts +2 -2
  83. package/dist/transport.d.ts.map +1 -1
  84. package/dist/user/payload.d.ts +3 -29
  85. package/dist/user/payload.d.ts.map +1 -1
  86. package/dist/user/retriever.d.ts +3 -9
  87. package/dist/user/retriever.d.ts.map +1 -1
  88. package/dist/util/decodeJSONString.d.ts.map +1 -1
  89. package/dist/util/zod.d.ts +1 -1
  90. package/dist/util/zod.d.ts.map +1 -1
  91. package/dist/workspace/lineplot/payload.d.ts +10 -26
  92. package/dist/workspace/lineplot/payload.d.ts.map +1 -1
  93. package/dist/workspace/log/payload.d.ts +10 -26
  94. package/dist/workspace/log/payload.d.ts.map +1 -1
  95. package/dist/workspace/payload.d.ts +14 -40
  96. package/dist/workspace/payload.d.ts.map +1 -1
  97. package/dist/workspace/schematic/payload.d.ts +13 -45
  98. package/dist/workspace/schematic/payload.d.ts.map +1 -1
  99. package/dist/workspace/table/payload.d.ts +13 -39
  100. package/dist/workspace/table/payload.d.ts.map +1 -1
  101. package/package.json +8 -8
  102. package/src/channel/channel.spec.ts +26 -27
  103. package/src/channel/client.ts +0 -9
  104. package/src/channel/payload.ts +22 -5
  105. package/src/channel/retriever.ts +12 -6
  106. package/src/client.ts +4 -4
  107. package/src/control/client.ts +5 -2
  108. package/src/control/state.spec.ts +1 -2
  109. package/src/control/state.ts +8 -3
  110. package/src/errors.spec.ts +5 -4
  111. package/src/errors.ts +21 -82
  112. package/src/framer/adapter.ts +22 -3
  113. package/src/framer/client.ts +38 -21
  114. package/src/framer/codec.spec.ts +303 -0
  115. package/src/framer/codec.ts +396 -0
  116. package/src/framer/deleter.spec.ts +51 -63
  117. package/src/framer/frame.ts +16 -5
  118. package/src/framer/iterator.spec.ts +45 -28
  119. package/src/framer/iterator.ts +6 -5
  120. package/src/framer/streamProxy.ts +1 -1
  121. package/src/framer/streamer.spec.ts +10 -27
  122. package/src/framer/streamer.ts +138 -22
  123. package/src/framer/writer.spec.ts +125 -150
  124. package/src/framer/writer.ts +74 -68
  125. package/src/hardware/device/client.ts +42 -10
  126. package/src/hardware/device/device.spec.ts +109 -1
  127. package/src/hardware/device/payload.ts +17 -3
  128. package/src/hardware/rack/client.ts +48 -8
  129. package/src/hardware/rack/payload.ts +16 -1
  130. package/src/hardware/rack/rack.spec.ts +36 -0
  131. package/src/hardware/task/payload.ts +9 -6
  132. package/src/hardware/task/task.spec.ts +9 -6
  133. package/src/index.ts +0 -2
  134. package/src/ontology/group/group.spec.ts +2 -2
  135. package/src/ontology/payload.ts +3 -3
  136. package/src/ranger/client.ts +3 -2
  137. package/src/ranger/ranger.spec.ts +9 -7
  138. package/src/testutil/indexedPair.ts +40 -0
  139. package/src/testutil/telem.ts +13 -0
  140. package/src/transport.ts +1 -2
  141. package/src/util/decodeJSONString.ts +2 -2
  142. package/src/util/retrieve.spec.ts +1 -1
@@ -7,13 +7,8 @@
7
7
  // License, use of this software will be governed by the Apache License, Version 2.0,
8
8
  // included in the file licenses/APL.txt.
9
9
 
10
- import {
11
- decodeError,
12
- errorZ,
13
- type Stream,
14
- type StreamClient,
15
- } from "@synnaxlabs/freighter";
16
- import { control } from "@synnaxlabs/x";
10
+ import { EOF, type Stream, type WebSocketClient } from "@synnaxlabs/freighter";
11
+ import { control, errors } from "@synnaxlabs/x";
17
12
  import {
18
13
  type CrudeSeries,
19
14
  type CrudeTimeStamp,
@@ -24,16 +19,16 @@ import { toArray } from "@synnaxlabs/x/toArray";
24
19
  import { z } from "zod";
25
20
 
26
21
  import { channel } from "@/channel";
22
+ import { SynnaxError } from "@/errors";
27
23
  import { WriteAdapter } from "@/framer/adapter";
24
+ import { WSWriterCodec } from "@/framer/codec";
28
25
  import { type Crude, frameZ } from "@/framer/frame";
29
- import { StreamProxy } from "@/framer/streamProxy";
30
26
 
31
- enum Command {
27
+ export enum WriterCommand {
32
28
  Open = 0,
33
29
  Write = 1,
34
30
  Commit = 2,
35
- Error = 3,
36
- SetAuthority = 4,
31
+ SetAuthority = 3,
37
32
  }
38
33
 
39
34
  export enum WriterMode {
@@ -60,12 +55,18 @@ const constructWriterMode = (mode: CrudeWriterMode): WriterMode => {
60
55
 
61
56
  export const ALWAYS_INDEX_PERSIST_ON_AUTO_COMMIT: TimeSpan = new TimeSpan(-1);
62
57
 
58
+ export class WriterClosedError extends SynnaxError.sub("writer_closed") {
59
+ constructor() {
60
+ super("WriterClosed");
61
+ }
62
+ }
63
+
63
64
  const netConfigZ = z.object({
64
65
  start: TimeStamp.z.optional(),
65
66
  controlSubject: control.subjectZ.optional(),
66
67
  keys: channel.keyZ.array().optional(),
67
- authorities: control.Authority.z.array().optional(),
68
- mode: z.nativeEnum(WriterMode).optional(),
68
+ authorities: control.authorityZ.array().optional(),
69
+ mode: z.enum(WriterMode).optional(),
69
70
  errOnUnauthorized: z.boolean().optional(),
70
71
  enableAutoCommit: z.boolean().optional(),
71
72
  autoIndexPersistInterval: TimeSpan.z.optional(),
@@ -74,17 +75,18 @@ const netConfigZ = z.object({
74
75
  interface Config extends z.infer<typeof netConfigZ> {}
75
76
 
76
77
  const reqZ = z.object({
77
- command: z.nativeEnum(Command),
78
+ command: z.enum(WriterCommand),
78
79
  config: netConfigZ.optional(),
79
80
  frame: frameZ.optional(),
81
+ buffer: z.instanceof(Uint8Array).optional(),
80
82
  });
81
83
 
82
- interface Request extends z.infer<typeof reqZ> {}
84
+ export interface WriteRequest extends z.infer<typeof reqZ> {}
83
85
 
84
86
  const resZ = z.object({
85
- ack: z.boolean(),
86
- command: z.nativeEnum(Command),
87
- error: errorZ.optional().nullable(),
87
+ command: z.enum(WriterCommand),
88
+ end: TimeStamp.z,
89
+ err: errors.payloadZ.optional(),
88
90
  });
89
91
 
90
92
  interface Response extends z.infer<typeof resZ> {}
@@ -114,6 +116,7 @@ export interface WriterConfig {
114
116
  // persisted. To persist every commit to guarantee minimal loss of data, set
115
117
  // auto_index_persist_interval to AlwaysAutoIndexPersist.
116
118
  autoIndexPersistInterval?: TimeSpan;
119
+ useExperimentalCodec?: boolean;
117
120
  }
118
121
 
119
122
  /**
@@ -156,34 +159,37 @@ export interface WriterConfig {
156
159
  */
157
160
  export class Writer {
158
161
  private static readonly ENDPOINT = "/frame/write";
159
- private readonly stream: StreamProxy<typeof reqZ, typeof resZ>;
162
+ private readonly stream: Stream<typeof reqZ, typeof resZ>;
160
163
  private readonly adapter: WriteAdapter;
161
- private errAccumulated: boolean = false;
164
+ private closeErr: Error | null = null;
162
165
 
163
166
  private constructor(stream: Stream<typeof reqZ, typeof resZ>, adapter: WriteAdapter) {
164
- this.stream = new StreamProxy("Writer", stream);
167
+ this.stream = stream;
165
168
  this.adapter = adapter;
166
169
  }
167
170
 
168
171
  static async _open(
169
172
  retriever: channel.Retriever,
170
- client: StreamClient,
173
+ client: WebSocketClient,
171
174
  {
172
175
  channels,
173
176
  start = TimeStamp.now(),
174
- authorities = control.Authority.ABSOLUTE,
177
+ authorities = control.ABSOLUTE_AUTHORITY,
175
178
  controlSubject: subject,
176
179
  mode = WriterMode.PersistStream,
177
180
  errOnUnauthorized = false,
178
181
  enableAutoCommit = false,
179
182
  autoIndexPersistInterval = TimeSpan.SECOND,
183
+ useExperimentalCodec = true,
180
184
  }: WriterConfig,
181
185
  ): Promise<Writer> {
182
186
  const adapter = await WriteAdapter.open(retriever, channels);
187
+ if (useExperimentalCodec)
188
+ client = client.withCodec(new WSWriterCodec(adapter.codec));
183
189
  const stream = await client.stream(Writer.ENDPOINT, reqZ, resZ);
184
190
  const writer = new Writer(stream, adapter);
185
191
  await writer.execute({
186
- command: Command.Open,
192
+ command: WriterCommand.Open,
187
193
  config: {
188
194
  start: new TimeStamp(start),
189
195
  keys: adapter.keys,
@@ -198,21 +204,13 @@ export class Writer {
198
204
  return writer;
199
205
  }
200
206
 
201
- private async checkForAccumulatedError(): Promise<boolean> {
202
- if (!this.errAccumulated && this.stream.received()) {
203
- this.errAccumulated = true;
204
- while (this.stream.received()) await this.stream.receive();
205
- }
206
- return this.errAccumulated;
207
- }
208
-
209
- async write(channel: channel.KeyOrName, data: CrudeSeries): Promise<boolean>;
210
- async write(channel: channel.KeysOrNames, data: CrudeSeries[]): Promise<boolean>;
211
- async write(frame: Crude | Record<channel.KeyOrName, CrudeSeries>): Promise<boolean>;
207
+ async write(channel: channel.KeyOrName, data: CrudeSeries): Promise<void>;
208
+ async write(channel: channel.KeysOrNames, data: CrudeSeries[]): Promise<void>;
209
+ async write(frame: Crude | Record<channel.KeyOrName, CrudeSeries>): Promise<void>;
212
210
  async write(
213
211
  channelsOrData: channel.Params | Record<channel.KeyOrName, CrudeSeries> | Crude,
214
212
  series?: CrudeSeries | CrudeSeries[],
215
- ): Promise<boolean>;
213
+ ): Promise<void>;
216
214
 
217
215
  /**
218
216
  * Writes the given frame to the database.
@@ -231,29 +229,29 @@ export class Writer {
231
229
  async write(
232
230
  channelsOrData: channel.Params | Record<channel.KeyOrName, CrudeSeries> | Crude,
233
231
  series?: CrudeSeries | CrudeSeries[],
234
- ): Promise<boolean> {
235
- if (await this.checkForAccumulatedError()) return false;
232
+ ): Promise<void> {
233
+ if (this.closeErr != null) throw this.closeErr;
234
+ if (this.stream.received()) return await this.close();
236
235
  const frame = await this.adapter.adapt(channelsOrData, series);
237
- this.stream.send({ command: Command.Write, frame: frame.toPayload() });
238
- return true;
236
+ this.stream.send({ command: WriterCommand.Write, frame: frame.toPayload() });
239
237
  }
240
238
 
241
- async setAuthority(value: number): Promise<boolean>;
239
+ async setAuthority(value: number): Promise<void>;
242
240
 
243
241
  async setAuthority(
244
242
  key: channel.KeyOrName,
245
243
  authority: control.Authority,
246
- ): Promise<boolean>;
244
+ ): Promise<void>;
247
245
 
248
246
  async setAuthority(
249
247
  value: Record<channel.KeyOrName, control.Authority>,
250
- ): Promise<boolean>;
248
+ ): Promise<void>;
251
249
 
252
250
  async setAuthority(
253
251
  value: Record<channel.KeyOrName, control.Authority> | channel.KeyOrName | number,
254
252
  authority?: control.Authority,
255
- ): Promise<boolean> {
256
- if (await this.checkForAccumulatedError()) return false;
253
+ ): Promise<void> {
254
+ if (this.closeErr != null) throw this.closeErr;
257
255
  let config: Config;
258
256
  if (typeof value === "number" && authority == null)
259
257
  config = { keys: [], authorities: [value] };
@@ -268,8 +266,7 @@ export class Writer {
268
266
  authorities: Object.values(oValue),
269
267
  };
270
268
  }
271
- const response = await this.execute({ command: Command.SetAuthority, config });
272
- return response.ack;
269
+ await this.execute({ command: WriterCommand.SetAuthority, config });
273
270
  }
274
271
 
275
272
  /**
@@ -280,19 +277,14 @@ export class Writer {
280
277
  * should acknowledge the error by calling the error method or closing the writer.
281
278
  * After the caller acknowledges the error, they can attempt to commit again.
282
279
  */
283
- async commit(): Promise<boolean> {
284
- if (await this.checkForAccumulatedError()) return false;
285
- const res = await this.execute({ command: Command.Commit });
286
- return res.ack;
287
- }
288
-
289
- /**
290
- * @returns The accumulated error, if any. This method will clear the writer's error
291
- * state, allowing the writer to be used again.
292
- */
293
- async error(): Promise<Error | null> {
294
- const res = await this.execute({ command: Command.Error });
295
- return res.error != null ? decodeError(res.error) : null;
280
+ async commit(): Promise<TimeStamp> {
281
+ if (this.closeErr != null) throw this.closeErr;
282
+ if (this.stream.received()) {
283
+ await this.closeInternal(null);
284
+ return TimeStamp.ZERO;
285
+ }
286
+ const res = await this.execute({ command: WriterCommand.Commit });
287
+ return res.end;
296
288
  }
297
289
 
298
290
  /**
@@ -301,19 +293,33 @@ export class Writer {
301
293
  * in a 'finally' block.
302
294
  */
303
295
  async close(): Promise<void> {
304
- await this.stream.closeAndAck();
296
+ await this.closeInternal(null);
305
297
  }
306
298
 
307
- async execute(req: Request): Promise<Response> {
308
- this.stream.send(req);
299
+ private async closeInternal(err: Error | null): Promise<null> {
300
+ if (this.closeErr != null) throw this.closeErr;
301
+ this.closeErr = err;
302
+ this.stream.closeSend();
309
303
  while (true) {
310
- const res = await this.stream.receive();
311
- if (res.command === req.command) return res;
312
- console.warn("writer received unexpected response", res);
304
+ if (this.closeErr != null) {
305
+ if (WriterClosedError.matches(this.closeErr)) return null;
306
+ throw this.closeErr;
307
+ }
308
+ const [res, err] = await this.stream.receive();
309
+ if (err != null) this.closeErr = EOF.matches(err) ? new WriterClosedError() : err;
310
+ else this.closeErr = errors.decode(res?.err);
313
311
  }
314
312
  }
315
313
 
316
- private get errorAccumulated(): boolean {
317
- return this.stream.received();
314
+ private async execute(req: WriteRequest): Promise<Response> {
315
+ const err = this.stream.send(req);
316
+ if (err != null) await this.closeInternal(err);
317
+ while (true) {
318
+ const [res, err] = await this.stream.receive();
319
+ if (err != null) await this.closeInternal(err);
320
+ const resErr = errors.decode(res?.err);
321
+ if (resErr != null) await this.closeInternal(resErr);
322
+ if (res?.command == req.command) return res;
323
+ }
318
324
  }
319
325
  }
@@ -12,7 +12,7 @@ import { toArray, type UnknownRecord } from "@synnaxlabs/x";
12
12
  import { type AsyncTermSearcher } from "@synnaxlabs/x/search";
13
13
  import { z } from "zod";
14
14
 
15
- import { type framer } from "@/framer";
15
+ import { framer } from "@/framer";
16
16
  import {
17
17
  type Device,
18
18
  deviceZ,
@@ -21,7 +21,10 @@ import {
21
21
  type New,
22
22
  newZ,
23
23
  ONTOLOGY_TYPE,
24
+ type State,
25
+ stateZ,
24
26
  } from "@/hardware/device/payload";
27
+ import { keyZ as rackKeyZ } from "@/hardware/rack/payload";
25
28
  import { ontology } from "@/ontology";
26
29
  import { signals } from "@/signals";
27
30
  import { checkForMultipleOrNoResults } from "@/util/retrieve";
@@ -29,6 +32,7 @@ import { nullableArrayZ } from "@/util/zod";
29
32
 
30
33
  const SET_CHANNEL_NAME = "sy_device_set";
31
34
  const DELETE_CHANNEL_NAME = "sy_device_delete";
35
+ const STATE_CHANNEL_NAME = "sy_device_state";
32
36
 
33
37
  const RETRIEVE_ENDPOINT = "/hardware/device/retrieve";
34
38
  const CREATE_ENDPOINT = "/hardware/device/create";
@@ -43,19 +47,26 @@ const deleteReqZ = z.object({ keys: keyZ.array() });
43
47
  const deleteResZ = z.object({});
44
48
 
45
49
  const retrieveReqZ = z.object({
46
- search: z.string().optional(),
47
- limit: z.number().optional(),
48
- offset: z.number().optional(),
49
50
  keys: keyZ.array().optional(),
50
51
  names: z.string().array().optional(),
51
52
  makes: z.string().array().optional(),
53
+ models: z.string().array().optional(),
54
+ locations: z.string().array().optional(),
55
+ racks: rackKeyZ.array().optional(),
56
+ search: z.string().optional(),
57
+ limit: z.number().optional(),
58
+ offset: z.number().optional(),
52
59
  ignoreNotFound: z.boolean().optional(),
60
+ includeState: z.boolean().optional(),
53
61
  });
54
62
 
55
63
  interface RetrieveRequest extends z.input<typeof retrieveReqZ> {}
56
64
 
57
65
  export interface RetrieveOptions
58
- extends Pick<RetrieveRequest, "limit" | "offset" | "makes" | "ignoreNotFound"> {}
66
+ extends Pick<
67
+ RetrieveRequest,
68
+ "limit" | "offset" | "makes" | "ignoreNotFound" | "includeState"
69
+ > {}
59
70
 
60
71
  interface PageOptions extends Pick<RetrieveOptions, "makes"> {}
61
72
 
@@ -75,26 +86,33 @@ export class Client implements AsyncTermSearcher<string, Key, Device> {
75
86
  Properties extends UnknownRecord = UnknownRecord,
76
87
  Make extends string = string,
77
88
  Model extends string = string,
78
- >(key: string, options?: RetrieveOptions): Promise<Device<Properties, Make, Model>>;
89
+ StateDetails extends {} = UnknownRecord,
90
+ >(
91
+ key: string,
92
+ options?: RetrieveOptions,
93
+ ): Promise<Device<Properties, Make, Model, StateDetails>>;
79
94
 
80
95
  async retrieve<
81
96
  Properties extends UnknownRecord = UnknownRecord,
82
97
  Make extends string = string,
83
98
  Model extends string = string,
99
+ StateDetails extends {} = UnknownRecord,
84
100
  >(
85
101
  keys: string[],
86
102
  options?: RetrieveOptions,
87
- ): Promise<Array<Device<Properties, Make, Model>>>;
103
+ ): Promise<Array<Device<Properties, Make, Model, StateDetails>>>;
88
104
 
89
105
  async retrieve<
90
106
  Properties extends UnknownRecord = UnknownRecord,
91
107
  Make extends string = string,
92
108
  Model extends string = string,
109
+ StateDetails extends {} = UnknownRecord,
93
110
  >(
94
111
  keys: string | string[],
95
112
  options?: RetrieveOptions,
96
113
  ): Promise<
97
- Device<Properties, Make, Model> | Array<Device<Properties, Make, Model>> | null
114
+ | Device<Properties, Make, Model, StateDetails>
115
+ | Array<Device<Properties, Make, Model, StateDetails>>
98
116
  > {
99
117
  const isSingle = !Array.isArray(keys);
100
118
  const res = await sendRequired(
@@ -106,8 +124,8 @@ export class Client implements AsyncTermSearcher<string, Key, Device> {
106
124
  );
107
125
  checkForMultipleOrNoResults("Device", keys, res.devices, isSingle);
108
126
  return isSingle
109
- ? (res.devices[0] as Device<Properties, Make, Model>)
110
- : (res.devices as Array<Device<Properties, Make, Model>>);
127
+ ? (res.devices[0] as Device<Properties, Make, Model, StateDetails>)
128
+ : (res.devices as Array<Device<Properties, Make, Model, StateDetails>>);
111
129
  }
112
130
 
113
131
  async search(term: string, options?: RetrieveOptions): Promise<Device[]> {
@@ -183,6 +201,20 @@ export class Client implements AsyncTermSearcher<string, Key, Device> {
183
201
  );
184
202
  }
185
203
 
204
+ async openStateObserver<Details extends {} = UnknownRecord>(): Promise<
205
+ framer.ObservableStreamer<State<Details>[]>
206
+ > {
207
+ return new framer.ObservableStreamer<State<Details>[]>(
208
+ await this.frameClient.openStreamer(STATE_CHANNEL_NAME),
209
+ (frame) => {
210
+ const s = frame.get(STATE_CHANNEL_NAME);
211
+ if (s.length === 0) return [null, false];
212
+ const states = s.parseJSON(stateZ);
213
+ return [states as State<Details>[], true];
214
+ },
215
+ );
216
+ }
217
+
186
218
  newSearcherWithOptions(
187
219
  options: RetrieveOptions,
188
220
  ): AsyncTermSearcher<string, Key, Device> {
@@ -7,7 +7,7 @@
7
7
  // License, use of this software will be governed by the Apache License, Version 2.0,
8
8
  // included in the file licenses/APL.txt.
9
9
 
10
- import { id } from "@synnaxlabs/x";
10
+ import { id, type UnknownRecord } from "@synnaxlabs/x";
11
11
  import { describe, expect, it } from "vitest";
12
12
 
13
13
  import { NotFoundError } from "@/errors";
@@ -108,5 +108,113 @@ describe("Device", async () => {
108
108
  }),
109
109
  ).rejects.toThrow(NotFoundError);
110
110
  });
111
+
112
+ describe("state", () => {
113
+ it("should not include state by default", async () => {
114
+ const d = await client.hardware.devices.create({
115
+ key: "SN_STATE_TEST1",
116
+ rack: testRack.key,
117
+ location: "Dev1",
118
+ name: "state_test1",
119
+ make: "ni",
120
+ model: "dog",
121
+ properties: { cat: "dog" },
122
+ });
123
+
124
+ const retrieved = await client.hardware.devices.retrieve(d.key);
125
+ expect(retrieved.state?.key).toHaveLength(0);
126
+ });
127
+
128
+ it("should include state when includeState is true", async () => {
129
+ const d = await client.hardware.devices.create({
130
+ key: "SN_STATE_TEST2",
131
+ rack: testRack.key,
132
+ location: "Dev1",
133
+ name: "state_test2",
134
+ make: "ni",
135
+ model: "dog",
136
+ properties: { cat: "dog" },
137
+ });
138
+
139
+ const retrieved = await client.hardware.devices.retrieve(d.key, {
140
+ includeState: true,
141
+ });
142
+ expect(retrieved.state).toBeDefined();
143
+ if (retrieved.state) {
144
+ expect(retrieved.state.variant).toBeDefined();
145
+ expect(retrieved.state.key).toBeDefined();
146
+ expect(retrieved.state.details).toBeDefined();
147
+ }
148
+ });
149
+
150
+ it("should include state for multiple devices", async () => {
151
+ const d1 = await client.hardware.devices.create({
152
+ key: "SN_STATE_TEST3",
153
+ rack: testRack.key,
154
+ location: "Dev1",
155
+ name: "state_test3",
156
+ make: "ni",
157
+ model: "dog",
158
+ properties: { cat: "dog" },
159
+ });
160
+
161
+ const d2 = await client.hardware.devices.create({
162
+ key: "SN_STATE_TEST4",
163
+ rack: testRack.key,
164
+ location: "Dev2",
165
+ name: "state_test4",
166
+ make: "ni",
167
+ model: "dog",
168
+ properties: { cat: "dog" },
169
+ });
170
+
171
+ const retrieved = await client.hardware.devices.retrieve([d1.key, d2.key], {
172
+ includeState: true,
173
+ });
174
+ expect(retrieved).toHaveLength(2);
175
+ retrieved.forEach((device) => {
176
+ expect(device.state).toBeDefined();
177
+ if (device.state) {
178
+ expect(device.state.variant).toBeDefined();
179
+ expect(device.state.key).toBeDefined();
180
+ expect(device.state.details).toBeDefined();
181
+ }
182
+ });
183
+ });
184
+
185
+ it("should handle state with type-safe details", async () => {
186
+ interface DeviceStateDetails {
187
+ status: string;
188
+ temperature: number;
189
+ }
190
+
191
+ const key = id.create();
192
+ await client.hardware.devices.create({
193
+ key,
194
+ rack: testRack.key,
195
+ location: "Dev1",
196
+ name: "state_test5",
197
+ make: "ni",
198
+ model: "dog",
199
+ properties: { cat: "dog" },
200
+ });
201
+
202
+ await expect
203
+ .poll(async () => {
204
+ const retrieved = await client.hardware.devices.retrieve<
205
+ UnknownRecord,
206
+ string,
207
+ string,
208
+ DeviceStateDetails
209
+ >(key, { includeState: true });
210
+ return (
211
+ retrieved.state !== undefined &&
212
+ retrieved.state.variant === "info" &&
213
+ retrieved.state.key === key
214
+ );
215
+ })
216
+ .toBeTruthy();
217
+ });
218
+ });
111
219
  });
112
220
  });
@@ -7,7 +7,7 @@
7
7
  // License, use of this software will be governed by the Apache License, Version 2.0,
8
8
  // included in the file licenses/APL.txt.
9
9
 
10
- import { binary, type UnknownRecord } from "@synnaxlabs/x";
10
+ import { binary, type UnknownRecord, unknownRecordZ } from "@synnaxlabs/x";
11
11
  import { z } from "zod";
12
12
 
13
13
  import { keyZ as rackKeyZ } from "@/hardware/rack/payload";
@@ -16,6 +16,17 @@ import { decodeJSONString } from "@/util/decodeJSONString";
16
16
  export const keyZ = z.string();
17
17
  export type Key = z.infer<typeof keyZ>;
18
18
 
19
+ export const stateZ = z.object({
20
+ key: keyZ,
21
+ variant: z.string(),
22
+ details: unknownRecordZ.or(z.string().transform(decodeJSONString)),
23
+ });
24
+
25
+ export interface State<Details extends {} = UnknownRecord>
26
+ extends Omit<z.infer<typeof stateZ>, "details"> {
27
+ details: Details;
28
+ }
29
+
19
30
  export const deviceZ = z.object({
20
31
  key: keyZ,
21
32
  rack: rackKeyZ,
@@ -24,17 +35,20 @@ export const deviceZ = z.object({
24
35
  model: z.string(),
25
36
  location: z.string(),
26
37
  configured: z.boolean().optional(),
27
- properties: z.record(z.unknown()).or(z.string().transform(decodeJSONString)),
38
+ properties: unknownRecordZ.or(z.string().transform(decodeJSONString)),
39
+ state: stateZ.optional(),
28
40
  });
29
41
 
30
42
  export interface Device<
31
43
  Properties extends UnknownRecord = UnknownRecord,
32
44
  Make extends string = string,
33
45
  Model extends string = string,
34
- > extends Omit<z.output<typeof deviceZ>, "properties"> {
46
+ StateDetails extends {} = UnknownRecord,
47
+ > extends Omit<z.output<typeof deviceZ>, "properties" | "state"> {
35
48
  properties: Properties;
36
49
  make: Make;
37
50
  model: Model;
51
+ state?: State<StateDetails>;
38
52
  }
39
53
 
40
54
  export const newZ = deviceZ.extend({