@deveye/types 0.20.3 → 0.21.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.
@@ -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,8 @@ 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
+ /** The plan `metricIntervals` applies. Default paid. */
246
+ paid?: boolean;
234
247
  }
235
248
 
236
249
  /** Replays the planned pieces; the summary appears once the last one is taken, as in the app. */
@@ -270,9 +283,21 @@ function recordingAgents(recorded: RecordedCalls, docker: TestAgents = {}): DevE
270
283
  isOnline: () => true,
271
284
  requestScan: req('requestScan'),
272
285
  pushConfig: (deviceId) => Promise.resolve(req('pushConfig')(deviceId)),
286
+ // The app's rule with the harness's plan: paid unless `paid: false`.
287
+ metricIntervals: (devices) =>
288
+ Promise.resolve(
289
+ new Map(
290
+ devices.map((d) => [
291
+ d.id,
292
+ d.metric_interval_seconds ??
293
+ DEFAULT_METRIC_INTERVAL_SECONDS[docker.paid === false ? 'free' : 'paid']
294
+ ])
295
+ )
296
+ ),
273
297
  requestSyncConfig: req('requestSyncConfig'),
274
298
  requestSyncScan: req('requestSyncScan'),
275
299
  requestSyncPush: req('requestSyncPush'),
300
+ requestSyncPushAck: req('requestSyncPushAck'),
276
301
  requestSyncApplyChunk: req('requestSyncApplyChunk'),
277
302
  requestSyncApplyStart: req('requestSyncApplyStart'),
278
303
  requestSyncApplyDir: req('requestSyncApplyDir'),
@@ -346,6 +371,36 @@ async function assertActiveIn(pauses: SdkPlanPauses, key: string, itemId: string
346
371
  }
347
372
  }
348
373
 
374
+ /**
375
+ * The app's rule for `quota.usage`: nothing counted when unlimited, a `stock`
376
+ * counted by its list, any other quota by its count.
377
+ */
378
+ function usageIn<Repo>(
379
+ quotas: FeatureServer<Repo>['quotas'],
380
+ repo: Repo,
381
+ limits: Record<string, number> | undefined,
382
+ owned: readonly number[]
383
+ ): SdkQuota['usage'] {
384
+ return async (key) => {
385
+ const limit = limits?.[key];
386
+ if (limit === undefined) return null;
387
+ const entry = quotas?.[key];
388
+ if (!entry) throw new Error(`quota « ${key} »: pass your server's quotas to the harness`);
389
+ const used = entry.list
390
+ ? (await entry.list(repo, owned)).length
391
+ : await (entry.count ?? (() => Promise.resolve(0)))(repo, owned);
392
+ return { used, limit };
393
+ };
394
+ }
395
+
396
+ function usageLookup(usages: readonly SdkAccountUsage[]) {
397
+ return (userId: number): SdkAccountUsage => {
398
+ const found = usages.find((u) => u.userId === userId);
399
+ if (!found) throw new FeatureError('not_found', `account ${userId} unknown`);
400
+ return found;
401
+ };
402
+ }
403
+
349
404
  function memoryDomains(domains: readonly SdkDomain[]) {
350
405
  return {
351
406
  in: (workspaceId: number) => domains.filter((d) => d.workspaceId === workspaceId),
@@ -386,8 +441,14 @@ export interface TestContextOverrides<Repo> {
386
441
  account?: SdkAccount;
387
442
  /** The plan's limits, by YOUR quota key. An absent key is unlimited. Default none. */
388
443
  quotaLimits?: Record<string, number>;
444
+ /** What `quota.paid()` answers. Default true, a self-hosted instance. */
445
+ paid?: boolean;
389
446
  /** The workspaces the owner account owns, handed to a quota counter. Default: the workspace of the call. */
390
447
  ownerWorkspaceIds?: readonly number[];
448
+ /** Your server's `quotas`: `quota.usage` counts through them. */
449
+ quotas?: FeatureServer<Repo>['quotas'];
450
+ /** What `deveye.usage` knows, by account. Default none. */
451
+ accountUsage?: readonly SdkAccountUsage[];
391
452
  /** The items the plan holds paused, by YOUR `stock` quota key. Default none. */
392
453
  pausedItems?: Record<string, readonly string[]>;
393
454
  canWrite?: boolean;
@@ -493,10 +554,26 @@ export function createTestContext<Repo = undefined>(
493
554
  email: `user${overrides.userId ?? 1}@deveye.test`,
494
555
  username: `user${overrides.userId ?? 1}`,
495
556
  isAdmin: overrides.isAdmin ?? false,
557
+ e2e: false,
558
+ suspended: false,
496
559
  created: 0
497
560
  }
498
561
  )
499
562
  },
563
+ // The app's rules: its own usage for anyone, any account's for a global administrator.
564
+ usage: {
565
+ of: async (userId) => {
566
+ if (userId !== (overrides.userId ?? 1) && !overrides.isAdmin) {
567
+ throw new FeatureError('forbidden', 'administrators only');
568
+ }
569
+ return usageLookup(overrides.accountUsage ?? [])(userId);
570
+ },
571
+ ofMany: async (userIds) => {
572
+ if (!overrides.isAdmin) throw new FeatureError('forbidden', 'administrators only');
573
+ const known = overrides.accountUsage ?? [];
574
+ return userIds.flatMap((id) => known.filter((u) => u.userId === id));
575
+ }
576
+ },
500
577
  ...overrides.deveye
501
578
  };
502
579
  const restrictions = new Map<string, ItemAccess>(
@@ -538,6 +615,7 @@ export function createTestContext<Repo = undefined>(
538
615
  quota: {
539
616
  ...pauses,
540
617
  limit: (key) => Promise.resolve(overrides.quotaLimits?.[key] ?? null),
618
+ paid: () => Promise.resolve(overrides.paid ?? true),
541
619
  // The exact rule of the app: never counted when unlimited, refused
542
620
  // once the count AFTER creation passes the limit.
543
621
  async assert(key, countAfter) {
@@ -551,6 +629,12 @@ export function createTestContext<Repo = undefined>(
551
629
  });
552
630
  }
553
631
  },
632
+ usage: usageIn(
633
+ overrides.quotas,
634
+ overrides.repo as Repo,
635
+ overrides.quotaLimits,
636
+ overrides.ownerWorkspaceIds ?? [workspaceId]
637
+ ),
554
638
  assertActive: (key, itemId) => assertActiveIn(pauses, key, itemId)
555
639
  },
556
640
  items: {
@@ -650,6 +734,8 @@ export interface RecordedServiceCalls extends RecordedCalls {
650
734
  liveChanges: number[];
651
735
  /** `live.changed` calls that named topics, as `{ workspaceId, topics }` (a bare beat is not listed here). */
652
736
  liveTopicChanges: { workspaceId: number; topics: readonly string[] }[];
737
+ /** Emails `accountMail.send` and `sendToAdmins` accepted, with the address they went to. */
738
+ mails: { userId: number; to: string; message: SdkAccountMailMessage }[];
653
739
  }
654
740
 
655
741
  export interface TestServiceDeps<Repo> extends FeatureServiceDeps<Repo> {
@@ -674,10 +760,20 @@ export interface TestServiceOverrides<Repo> {
674
760
  archives?: Readonly<Record<string, TestFolderArchive | Error>>;
675
761
  /** What `deps.access` answers. Default: every member holds every right. */
676
762
  access?: Partial<FeatureServiceDeps['access']>;
677
- /** The accounts `deps.accounts` knows. Default none. */
763
+ /** The accounts `deps.accounts` knows, and `deps.accountMail` writes to. Default none. */
678
764
  accounts?: readonly SdkAccount[];
765
+ /** What `deps.accountMail.configured` answers. Default true. */
766
+ mailConfigured?: boolean;
679
767
  /** The plan's limits `deps.quotaFor` applies, by YOUR quota key. Default none (unlimited). */
680
768
  quotaLimits?: Record<string, number>;
769
+ /** What `quotaFor(...).paid()` answers. Default true, a self-hosted instance. */
770
+ paid?: boolean;
771
+ /** What `deps.objects(...)` returns. Default one {@link memoryObjectStore} for every `localDir`. */
772
+ objects?: SdkObjectStore;
773
+ /** Your server's `quotas`: `quotaFor(...).usage` counts through them. */
774
+ quotas?: FeatureServer<Repo>['quotas'];
775
+ /** What `deps.usage` knows, by account. Default none. */
776
+ accountUsage?: readonly SdkAccountUsage[];
681
777
  /** The items the plan holds paused (`deps.pauses`), by YOUR `stock` quota key. Default none. */
682
778
  pausedItems?: Record<string, readonly string[]>;
683
779
  /** What `deveyeFor(...).notify.hasRoute` answers. Default true. */
@@ -715,7 +811,8 @@ export function createTestServiceDeps<Repo = undefined>(
715
811
  accountChanges: [],
716
812
  tickers: [],
717
813
  liveChanges: [],
718
- liveTopicChanges: []
814
+ liveTopicChanges: [],
815
+ mails: []
719
816
  };
720
817
  const stores = new Map<number, TestFeatureStore>();
721
818
  const sealedBytes = new Map<string, Uint8Array>();
@@ -727,6 +824,7 @@ export function createTestServiceDeps<Repo = undefined>(
727
824
  );
728
825
  const devices = recordingDevices(overrides.devices ?? []);
729
826
  const pauses = memoryPauses(overrides.pausedItems);
827
+ const objects = overrides.objects ?? memoryObjectStore();
730
828
  return {
731
829
  recorded,
732
830
  stores,
@@ -792,6 +890,7 @@ export function createTestServiceDeps<Repo = undefined>(
792
890
  quotaFor: () => ({
793
891
  ...pauses,
794
892
  limit: (key) => Promise.resolve(overrides.quotaLimits?.[key] ?? null),
893
+ paid: () => Promise.resolve(overrides.paid ?? true),
795
894
  async assert(key, countAfter) {
796
895
  const limit = overrides.quotaLimits?.[key];
797
896
  if (limit === undefined) return;
@@ -802,6 +901,12 @@ export function createTestServiceDeps<Repo = undefined>(
802
901
  });
803
902
  }
804
903
  },
904
+ usage: usageIn(
905
+ overrides.quotas,
906
+ overrides.repo as Repo,
907
+ overrides.quotaLimits,
908
+ overrides.workspaceIds ?? [1]
909
+ ),
805
910
  assertActive: (key, itemId) => assertActiveIn(pauses, key, itemId)
806
911
  }),
807
912
  pauses,
@@ -835,12 +940,45 @@ export function createTestServiceDeps<Repo = undefined>(
835
940
  return Promise.resolve(
836
941
  found.slice(0, Math.min(Math.max(1, Math.trunc(limit ?? 20)), 50))
837
942
  );
943
+ },
944
+ all: () => Promise.resolve([...(overrides.accounts ?? [])])
945
+ },
946
+ usage: {
947
+ of: async (userId) => usageLookup(overrides.accountUsage ?? [])(userId),
948
+ ofMany: async (userIds) => {
949
+ const known = overrides.accountUsage ?? [];
950
+ return userIds.flatMap((id) => known.filter((u) => u.userId === id));
951
+ }
952
+ },
953
+ accountMail: {
954
+ configured: overrides.mailConfigured ?? true,
955
+ send(userId, message) {
956
+ if (overrides.mailConfigured === false) {
957
+ return Promise.reject(new FeatureError('conflict', 'no mail transport'));
958
+ }
959
+ const to = (overrides.accounts ?? []).find((a) => a.id === userId)?.email;
960
+ if (to === undefined) {
961
+ return Promise.reject(
962
+ new FeatureError('not_found', `account ${userId} unknown`)
963
+ );
964
+ }
965
+ recorded.mails.push({ userId, to, message });
966
+ return Promise.resolve(to);
967
+ },
968
+ sendToAdmins(message) {
969
+ if (overrides.mailConfigured === false) {
970
+ return Promise.reject(new FeatureError('conflict', 'no mail transport'));
971
+ }
972
+ const admins = (overrides.accounts ?? []).filter((a) => a.isAdmin && !a.suspended);
973
+ for (const a of admins) recorded.mails.push({ userId: a.id, to: a.email, message });
974
+ return Promise.resolve(admins.map((a) => a.email));
838
975
  }
839
976
  },
840
977
  audit: (entry) => {
841
978
  recorded.audits.push({ action: entry.action, description: entry.description });
842
979
  },
843
980
  agents: recordingAgents(recorded, overrides),
981
+ objects: () => objects,
844
982
  access: {
845
983
  feature: overrides.access?.feature ?? (() => Promise.resolve({ ok: true })),
846
984
  device: overrides.access?.device ?? (() => Promise.resolve({ ok: true }))
@@ -893,6 +1031,77 @@ export function testDomain(over: Partial<SdkDomain> & { id: number; host: string
893
1031
  };
894
1032
  }
895
1033
 
1034
+ /** An in-memory {@link SdkObjectStore}, with its objects exposed for assertions. */
1035
+ export interface MemoryObjectStore extends SdkObjectStore {
1036
+ readonly objects: Map<string, Buffer>;
1037
+ }
1038
+
1039
+ function assertTestKey(key: string): void {
1040
+ if (!key || key.startsWith('/') || key.includes('\0') || key.split('/').includes('..')) {
1041
+ throw new Error(`invalid object key « ${key} »`);
1042
+ }
1043
+ }
1044
+
1045
+ /**
1046
+ * The object store of the harness: `kind` says `'s3'` by default so a test
1047
+ * exercises the remote path; the spool is a real directory, since partial
1048
+ * uploads are written there with plain `fs`.
1049
+ */
1050
+ export function memoryObjectStore(
1051
+ opts: { kind?: 'local' | 's3'; spoolDir?: string; ephemeralRoot?: string } = {}
1052
+ ): MemoryObjectStore {
1053
+ const objects = new Map<string, Buffer>();
1054
+ const spool = opts.spoolDir ?? path.join(os.tmpdir(), `deveye-spool-${process.pid}`);
1055
+ return {
1056
+ objects,
1057
+ kind: opts.kind ?? 's3',
1058
+ describe: () => 'mémoire',
1059
+ async put(key, body) {
1060
+ assertTestKey(key);
1061
+ const parts: Buffer[] = [];
1062
+ if (body instanceof Uint8Array) parts.push(Buffer.from(body));
1063
+ else for await (const chunk of body) parts.push(Buffer.from(chunk));
1064
+ const bytes = Buffer.concat(parts);
1065
+ objects.set(key, bytes);
1066
+ return { size: bytes.length };
1067
+ },
1068
+ async putFile(key, localPath) {
1069
+ assertTestKey(key);
1070
+ const bytes = await readFile(localPath);
1071
+ objects.set(key, bytes);
1072
+ await rm(localPath, { force: true });
1073
+ return { size: bytes.length };
1074
+ },
1075
+ async *get(key, range) {
1076
+ const bytes = objects.get(key);
1077
+ if (!bytes) throw new Error(`no object « ${key} »`);
1078
+ const start = range?.start ?? 0;
1079
+ const end = range?.end === undefined ? bytes.length : range.end + 1;
1080
+ yield bytes.subarray(start, end);
1081
+ },
1082
+ head: (key) => {
1083
+ const bytes = objects.get(key);
1084
+ return Promise.resolve(bytes ? { size: bytes.length } : null);
1085
+ },
1086
+ async *list(prefix) {
1087
+ for (const [key, bytes] of [...objects]) {
1088
+ if (key.startsWith(prefix)) yield { key, size: bytes.length };
1089
+ }
1090
+ },
1091
+ delete: (key) => {
1092
+ objects.delete(key);
1093
+ return Promise.resolve();
1094
+ },
1095
+ deletePrefix: (prefix) => {
1096
+ if (!prefix.endsWith('/')) throw new Error(`prefix « ${prefix} » must end with /`);
1097
+ for (const key of [...objects.keys()]) if (key.startsWith(prefix)) objects.delete(key);
1098
+ return Promise.resolve();
1099
+ },
1100
+ spoolDir: () => spool,
1101
+ ephemeralRoot: () => Promise.resolve(opts.ephemeralRoot ?? null)
1102
+ };
1103
+ }
1104
+
896
1105
  /**
897
1106
  * What the `domains` hooks of a server entry receive, in memory: identity
898
1107
  * cipher, one store per workspace, and lookups that find nothing unless `dns`