@deveye/types 0.20.3 → 0.21.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.
@@ -1,4 +1,9 @@
1
+ import { readFile, rm } from 'node:fs/promises';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+
1
5
  import type { ZodType } from 'zod';
6
+ import { DEFAULT_METRIC_INTERVAL_SECONDS } from '../domain/device';
2
7
  import type { ItemAccess } from '../domain/sharing';
3
8
  import type { PathExclusion } from '../domain/pathExclusions';
4
9
  import { normaliseDomainHost } from './domains';
@@ -9,18 +14,23 @@ import {
9
14
  type AgentFolderArchiveSummary,
10
15
  type DevEyeFacade,
11
16
  type FeatureDomainsContext,
17
+ type FeatureServer,
12
18
  type SdkDns,
13
19
  type SdkDomain,
14
20
  type FeatureServiceDeps,
15
21
  type FeatureStore,
16
22
  type SdkAccount,
23
+ type SdkAccountMailMessage,
24
+ type SdkAccountUsage,
17
25
  type SdkCipher,
18
26
  type SdkDevice,
19
27
  type SdkFeatureContext,
20
28
  type SdkLogger,
29
+ type SdkObjectStore,
21
30
  type SdkOrigins,
22
31
  type SdkPlanPauses,
23
32
  type SdkProviders,
33
+ type SdkQuota,
24
34
  type SdkTelemetry,
25
35
  type SdkTelemetrySnapshot,
26
36
  type StorageEncryption,
@@ -179,6 +189,7 @@ export function testDevice(over: Partial<SdkDevice> & { id: string }): SdkDevice
179
189
  ownerUserId: 1,
180
190
  workspaceId: 1,
181
191
  metricIntervalSeconds: null,
192
+ effectiveMetricIntervalSeconds: 60,
182
193
  report: null,
183
194
  ...over
184
195
  };
@@ -231,6 +242,9 @@ interface TestAgents {
231
242
  dockerInventory?: DevEyeFacade['agents']['dockerInventory'];
232
243
  /** By device id. A device without an entry answers nothing: its stream throws. */
233
244
  archives?: Readonly<Record<string, TestFolderArchive | Error>>;
245
+ openTcp?: DevEyeFacade['agents']['openTcp'];
246
+ /** The plan `metricIntervals` applies. Default paid. */
247
+ paid?: boolean;
234
248
  }
235
249
 
236
250
  /** Replays the planned pieces; the summary appears once the last one is taken, as in the app. */
@@ -270,9 +284,21 @@ function recordingAgents(recorded: RecordedCalls, docker: TestAgents = {}): DevE
270
284
  isOnline: () => true,
271
285
  requestScan: req('requestScan'),
272
286
  pushConfig: (deviceId) => Promise.resolve(req('pushConfig')(deviceId)),
287
+ // The app's rule with the harness's plan: paid unless `paid: false`.
288
+ metricIntervals: (devices) =>
289
+ Promise.resolve(
290
+ new Map(
291
+ devices.map((d) => [
292
+ d.id,
293
+ d.metric_interval_seconds ??
294
+ DEFAULT_METRIC_INTERVAL_SECONDS[docker.paid === false ? 'free' : 'paid']
295
+ ])
296
+ )
297
+ ),
273
298
  requestSyncConfig: req('requestSyncConfig'),
274
299
  requestSyncScan: req('requestSyncScan'),
275
300
  requestSyncPush: req('requestSyncPush'),
301
+ requestSyncPushAck: req('requestSyncPushAck'),
276
302
  requestSyncApplyChunk: req('requestSyncApplyChunk'),
277
303
  requestSyncApplyStart: req('requestSyncApplyStart'),
278
304
  requestSyncApplyDir: req('requestSyncApplyDir'),
@@ -309,6 +335,12 @@ function recordingAgents(recorded: RecordedCalls, docker: TestAgents = {}): DevE
309
335
  recorded.agentRequests.push({ method: 'archiveFolder', deviceId });
310
336
  recorded.archiveRequests.push({ deviceId, ...request });
311
337
  return replayedArchive(docker.archives?.[deviceId]);
338
+ },
339
+ openTcp(deviceId, target) {
340
+ recorded.agentRequests.push({ method: 'openTcp', deviceId });
341
+ return docker.openTcp
342
+ ? docker.openTcp(deviceId, target)
343
+ : Promise.reject(new Error('La machine n’est pas connectée.'));
312
344
  }
313
345
  };
314
346
  }
@@ -346,6 +378,36 @@ async function assertActiveIn(pauses: SdkPlanPauses, key: string, itemId: string
346
378
  }
347
379
  }
348
380
 
381
+ /**
382
+ * The app's rule for `quota.usage`: nothing counted when unlimited, a `stock`
383
+ * counted by its list, any other quota by its count.
384
+ */
385
+ function usageIn<Repo>(
386
+ quotas: FeatureServer<Repo>['quotas'],
387
+ repo: Repo,
388
+ limits: Record<string, number> | undefined,
389
+ owned: readonly number[]
390
+ ): SdkQuota['usage'] {
391
+ return async (key) => {
392
+ const limit = limits?.[key];
393
+ if (limit === undefined) return null;
394
+ const entry = quotas?.[key];
395
+ if (!entry) throw new Error(`quota « ${key} »: pass your server's quotas to the harness`);
396
+ const used = entry.list
397
+ ? (await entry.list(repo, owned)).length
398
+ : await (entry.count ?? (() => Promise.resolve(0)))(repo, owned);
399
+ return { used, limit };
400
+ };
401
+ }
402
+
403
+ function usageLookup(usages: readonly SdkAccountUsage[]) {
404
+ return (userId: number): SdkAccountUsage => {
405
+ const found = usages.find((u) => u.userId === userId);
406
+ if (!found) throw new FeatureError('not_found', `account ${userId} unknown`);
407
+ return found;
408
+ };
409
+ }
410
+
349
411
  function memoryDomains(domains: readonly SdkDomain[]) {
350
412
  return {
351
413
  in: (workspaceId: number) => domains.filter((d) => d.workspaceId === workspaceId),
@@ -386,8 +448,14 @@ export interface TestContextOverrides<Repo> {
386
448
  account?: SdkAccount;
387
449
  /** The plan's limits, by YOUR quota key. An absent key is unlimited. Default none. */
388
450
  quotaLimits?: Record<string, number>;
451
+ /** What `quota.paid()` answers. Default true, a self-hosted instance. */
452
+ paid?: boolean;
389
453
  /** The workspaces the owner account owns, handed to a quota counter. Default: the workspace of the call. */
390
454
  ownerWorkspaceIds?: readonly number[];
455
+ /** Your server's `quotas`: `quota.usage` counts through them. */
456
+ quotas?: FeatureServer<Repo>['quotas'];
457
+ /** What `deveye.usage` knows, by account. Default none. */
458
+ accountUsage?: readonly SdkAccountUsage[];
391
459
  /** The items the plan holds paused, by YOUR `stock` quota key. Default none. */
392
460
  pausedItems?: Record<string, readonly string[]>;
393
461
  canWrite?: boolean;
@@ -420,6 +488,8 @@ export interface TestContextOverrides<Repo> {
420
488
  dockerInventory?: DevEyeFacade['agents']['dockerInventory'];
421
489
  /** What `deveye.agents.archiveFolder` streams, by device id. Default none: the stream throws. */
422
490
  archives?: Readonly<Record<string, TestFolderArchive | Error>>;
491
+ /** What `deveye.agents.openTcp` resolves. Default a rejection, as for an offline device. */
492
+ openTcp?: DevEyeFacade['agents']['openTcp'];
423
493
  /** Instants `deveye.telemetry.snapshot` answers (matched within a second). Default none. */
424
494
  snapshots?: readonly SdkTelemetrySnapshot[];
425
495
  /** Override facade members entirely when the defaults are not enough. */
@@ -493,10 +563,26 @@ export function createTestContext<Repo = undefined>(
493
563
  email: `user${overrides.userId ?? 1}@deveye.test`,
494
564
  username: `user${overrides.userId ?? 1}`,
495
565
  isAdmin: overrides.isAdmin ?? false,
566
+ e2e: false,
567
+ suspended: false,
496
568
  created: 0
497
569
  }
498
570
  )
499
571
  },
572
+ // The app's rules: its own usage for anyone, any account's for a global administrator.
573
+ usage: {
574
+ of: async (userId) => {
575
+ if (userId !== (overrides.userId ?? 1) && !overrides.isAdmin) {
576
+ throw new FeatureError('forbidden', 'administrators only');
577
+ }
578
+ return usageLookup(overrides.accountUsage ?? [])(userId);
579
+ },
580
+ ofMany: async (userIds) => {
581
+ if (!overrides.isAdmin) throw new FeatureError('forbidden', 'administrators only');
582
+ const known = overrides.accountUsage ?? [];
583
+ return userIds.flatMap((id) => known.filter((u) => u.userId === id));
584
+ }
585
+ },
500
586
  ...overrides.deveye
501
587
  };
502
588
  const restrictions = new Map<string, ItemAccess>(
@@ -538,6 +624,7 @@ export function createTestContext<Repo = undefined>(
538
624
  quota: {
539
625
  ...pauses,
540
626
  limit: (key) => Promise.resolve(overrides.quotaLimits?.[key] ?? null),
627
+ paid: () => Promise.resolve(overrides.paid ?? true),
541
628
  // The exact rule of the app: never counted when unlimited, refused
542
629
  // once the count AFTER creation passes the limit.
543
630
  async assert(key, countAfter) {
@@ -551,6 +638,12 @@ export function createTestContext<Repo = undefined>(
551
638
  });
552
639
  }
553
640
  },
641
+ usage: usageIn(
642
+ overrides.quotas,
643
+ overrides.repo as Repo,
644
+ overrides.quotaLimits,
645
+ overrides.ownerWorkspaceIds ?? [workspaceId]
646
+ ),
554
647
  assertActive: (key, itemId) => assertActiveIn(pauses, key, itemId)
555
648
  },
556
649
  items: {
@@ -650,6 +743,8 @@ export interface RecordedServiceCalls extends RecordedCalls {
650
743
  liveChanges: number[];
651
744
  /** `live.changed` calls that named topics, as `{ workspaceId, topics }` (a bare beat is not listed here). */
652
745
  liveTopicChanges: { workspaceId: number; topics: readonly string[] }[];
746
+ /** Emails `accountMail.send` and `sendToAdmins` accepted, with the address they went to. */
747
+ mails: { userId: number; to: string; message: SdkAccountMailMessage }[];
653
748
  }
654
749
 
655
750
  export interface TestServiceDeps<Repo> extends FeatureServiceDeps<Repo> {
@@ -672,12 +767,24 @@ export interface TestServiceOverrides<Repo> {
672
767
  dockerInventory?: DevEyeFacade['agents']['dockerInventory'];
673
768
  /** What `deps.agents.archiveFolder` streams, by device id. Default none: the stream throws. */
674
769
  archives?: Readonly<Record<string, TestFolderArchive | Error>>;
770
+ /** What `deps.agents.openTcp` resolves. Default a rejection, as for an offline device. */
771
+ openTcp?: DevEyeFacade['agents']['openTcp'];
675
772
  /** What `deps.access` answers. Default: every member holds every right. */
676
773
  access?: Partial<FeatureServiceDeps['access']>;
677
- /** The accounts `deps.accounts` knows. Default none. */
774
+ /** The accounts `deps.accounts` knows, and `deps.accountMail` writes to. Default none. */
678
775
  accounts?: readonly SdkAccount[];
776
+ /** What `deps.accountMail.configured` answers. Default true. */
777
+ mailConfigured?: boolean;
679
778
  /** The plan's limits `deps.quotaFor` applies, by YOUR quota key. Default none (unlimited). */
680
779
  quotaLimits?: Record<string, number>;
780
+ /** What `quotaFor(...).paid()` answers. Default true, a self-hosted instance. */
781
+ paid?: boolean;
782
+ /** What `deps.objects(...)` returns. Default one {@link memoryObjectStore} for every `localDir`. */
783
+ objects?: SdkObjectStore;
784
+ /** Your server's `quotas`: `quotaFor(...).usage` counts through them. */
785
+ quotas?: FeatureServer<Repo>['quotas'];
786
+ /** What `deps.usage` knows, by account. Default none. */
787
+ accountUsage?: readonly SdkAccountUsage[];
681
788
  /** The items the plan holds paused (`deps.pauses`), by YOUR `stock` quota key. Default none. */
682
789
  pausedItems?: Record<string, readonly string[]>;
683
790
  /** What `deveyeFor(...).notify.hasRoute` answers. Default true. */
@@ -715,7 +822,8 @@ export function createTestServiceDeps<Repo = undefined>(
715
822
  accountChanges: [],
716
823
  tickers: [],
717
824
  liveChanges: [],
718
- liveTopicChanges: []
825
+ liveTopicChanges: [],
826
+ mails: []
719
827
  };
720
828
  const stores = new Map<number, TestFeatureStore>();
721
829
  const sealedBytes = new Map<string, Uint8Array>();
@@ -727,6 +835,7 @@ export function createTestServiceDeps<Repo = undefined>(
727
835
  );
728
836
  const devices = recordingDevices(overrides.devices ?? []);
729
837
  const pauses = memoryPauses(overrides.pausedItems);
838
+ const objects = overrides.objects ?? memoryObjectStore();
730
839
  return {
731
840
  recorded,
732
841
  stores,
@@ -792,6 +901,7 @@ export function createTestServiceDeps<Repo = undefined>(
792
901
  quotaFor: () => ({
793
902
  ...pauses,
794
903
  limit: (key) => Promise.resolve(overrides.quotaLimits?.[key] ?? null),
904
+ paid: () => Promise.resolve(overrides.paid ?? true),
795
905
  async assert(key, countAfter) {
796
906
  const limit = overrides.quotaLimits?.[key];
797
907
  if (limit === undefined) return;
@@ -802,6 +912,12 @@ export function createTestServiceDeps<Repo = undefined>(
802
912
  });
803
913
  }
804
914
  },
915
+ usage: usageIn(
916
+ overrides.quotas,
917
+ overrides.repo as Repo,
918
+ overrides.quotaLimits,
919
+ overrides.workspaceIds ?? [1]
920
+ ),
805
921
  assertActive: (key, itemId) => assertActiveIn(pauses, key, itemId)
806
922
  }),
807
923
  pauses,
@@ -835,12 +951,45 @@ export function createTestServiceDeps<Repo = undefined>(
835
951
  return Promise.resolve(
836
952
  found.slice(0, Math.min(Math.max(1, Math.trunc(limit ?? 20)), 50))
837
953
  );
954
+ },
955
+ all: () => Promise.resolve([...(overrides.accounts ?? [])])
956
+ },
957
+ usage: {
958
+ of: async (userId) => usageLookup(overrides.accountUsage ?? [])(userId),
959
+ ofMany: async (userIds) => {
960
+ const known = overrides.accountUsage ?? [];
961
+ return userIds.flatMap((id) => known.filter((u) => u.userId === id));
962
+ }
963
+ },
964
+ accountMail: {
965
+ configured: overrides.mailConfigured ?? true,
966
+ send(userId, message) {
967
+ if (overrides.mailConfigured === false) {
968
+ return Promise.reject(new FeatureError('conflict', 'no mail transport'));
969
+ }
970
+ const to = (overrides.accounts ?? []).find((a) => a.id === userId)?.email;
971
+ if (to === undefined) {
972
+ return Promise.reject(
973
+ new FeatureError('not_found', `account ${userId} unknown`)
974
+ );
975
+ }
976
+ recorded.mails.push({ userId, to, message });
977
+ return Promise.resolve(to);
978
+ },
979
+ sendToAdmins(message) {
980
+ if (overrides.mailConfigured === false) {
981
+ return Promise.reject(new FeatureError('conflict', 'no mail transport'));
982
+ }
983
+ const admins = (overrides.accounts ?? []).filter((a) => a.isAdmin && !a.suspended);
984
+ for (const a of admins) recorded.mails.push({ userId: a.id, to: a.email, message });
985
+ return Promise.resolve(admins.map((a) => a.email));
838
986
  }
839
987
  },
840
988
  audit: (entry) => {
841
989
  recorded.audits.push({ action: entry.action, description: entry.description });
842
990
  },
843
991
  agents: recordingAgents(recorded, overrides),
992
+ objects: () => objects,
844
993
  access: {
845
994
  feature: overrides.access?.feature ?? (() => Promise.resolve({ ok: true })),
846
995
  device: overrides.access?.device ?? (() => Promise.resolve({ ok: true }))
@@ -893,6 +1042,77 @@ export function testDomain(over: Partial<SdkDomain> & { id: number; host: string
893
1042
  };
894
1043
  }
895
1044
 
1045
+ /** An in-memory {@link SdkObjectStore}, with its objects exposed for assertions. */
1046
+ export interface MemoryObjectStore extends SdkObjectStore {
1047
+ readonly objects: Map<string, Buffer>;
1048
+ }
1049
+
1050
+ function assertTestKey(key: string): void {
1051
+ if (!key || key.startsWith('/') || key.includes('\0') || key.split('/').includes('..')) {
1052
+ throw new Error(`invalid object key « ${key} »`);
1053
+ }
1054
+ }
1055
+
1056
+ /**
1057
+ * The object store of the harness: `kind` says `'s3'` by default so a test
1058
+ * exercises the remote path; the spool is a real directory, since partial
1059
+ * uploads are written there with plain `fs`.
1060
+ */
1061
+ export function memoryObjectStore(
1062
+ opts: { kind?: 'local' | 's3'; spoolDir?: string; ephemeralRoot?: string } = {}
1063
+ ): MemoryObjectStore {
1064
+ const objects = new Map<string, Buffer>();
1065
+ const spool = opts.spoolDir ?? path.join(os.tmpdir(), `deveye-spool-${process.pid}`);
1066
+ return {
1067
+ objects,
1068
+ kind: opts.kind ?? 's3',
1069
+ describe: () => 'mémoire',
1070
+ async put(key, body) {
1071
+ assertTestKey(key);
1072
+ const parts: Buffer[] = [];
1073
+ if (body instanceof Uint8Array) parts.push(Buffer.from(body));
1074
+ else for await (const chunk of body) parts.push(Buffer.from(chunk));
1075
+ const bytes = Buffer.concat(parts);
1076
+ objects.set(key, bytes);
1077
+ return { size: bytes.length };
1078
+ },
1079
+ async putFile(key, localPath) {
1080
+ assertTestKey(key);
1081
+ const bytes = await readFile(localPath);
1082
+ objects.set(key, bytes);
1083
+ await rm(localPath, { force: true });
1084
+ return { size: bytes.length };
1085
+ },
1086
+ async *get(key, range) {
1087
+ const bytes = objects.get(key);
1088
+ if (!bytes) throw new Error(`no object « ${key} »`);
1089
+ const start = range?.start ?? 0;
1090
+ const end = range?.end === undefined ? bytes.length : range.end + 1;
1091
+ yield bytes.subarray(start, end);
1092
+ },
1093
+ head: (key) => {
1094
+ const bytes = objects.get(key);
1095
+ return Promise.resolve(bytes ? { size: bytes.length } : null);
1096
+ },
1097
+ async *list(prefix) {
1098
+ for (const [key, bytes] of [...objects]) {
1099
+ if (key.startsWith(prefix)) yield { key, size: bytes.length };
1100
+ }
1101
+ },
1102
+ delete: (key) => {
1103
+ objects.delete(key);
1104
+ return Promise.resolve();
1105
+ },
1106
+ deletePrefix: (prefix) => {
1107
+ if (!prefix.endsWith('/')) throw new Error(`prefix « ${prefix} » must end with /`);
1108
+ for (const key of [...objects.keys()]) if (key.startsWith(prefix)) objects.delete(key);
1109
+ return Promise.resolve();
1110
+ },
1111
+ spoolDir: () => spool,
1112
+ ephemeralRoot: () => Promise.resolve(opts.ephemeralRoot ?? null)
1113
+ };
1114
+ }
1115
+
896
1116
  /**
897
1117
  * What the `domains` hooks of a server entry receive, in memory: identity
898
1118
  * cipher, one store per workspace, and lookups that find nothing unless `dns`