@deveye/types 0.20.2 → 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'),
@@ -283,7 +308,6 @@ function recordingAgents(recorded: RecordedCalls, docker: TestAgents = {}): DevE
283
308
  publishSyncState: () => undefined,
284
309
  requestDestroy: req('requestDestroy'),
285
310
  disconnectAgent: req('disconnectAgent'),
286
- resetAgentSession: req('resetAgentSession'),
287
311
  // Nothing synced: a test of the self-update flag feeds a manifest to
288
312
  // the module's own pure helper.
289
313
  servedManifest: () => Promise.resolve(null),
@@ -347,6 +371,36 @@ async function assertActiveIn(pauses: SdkPlanPauses, key: string, itemId: string
347
371
  }
348
372
  }
349
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
+
350
404
  function memoryDomains(domains: readonly SdkDomain[]) {
351
405
  return {
352
406
  in: (workspaceId: number) => domains.filter((d) => d.workspaceId === workspaceId),
@@ -387,8 +441,14 @@ export interface TestContextOverrides<Repo> {
387
441
  account?: SdkAccount;
388
442
  /** The plan's limits, by YOUR quota key. An absent key is unlimited. Default none. */
389
443
  quotaLimits?: Record<string, number>;
444
+ /** What `quota.paid()` answers. Default true, a self-hosted instance. */
445
+ paid?: boolean;
390
446
  /** The workspaces the owner account owns, handed to a quota counter. Default: the workspace of the call. */
391
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[];
392
452
  /** The items the plan holds paused, by YOUR `stock` quota key. Default none. */
393
453
  pausedItems?: Record<string, readonly string[]>;
394
454
  canWrite?: boolean;
@@ -494,10 +554,26 @@ export function createTestContext<Repo = undefined>(
494
554
  email: `user${overrides.userId ?? 1}@deveye.test`,
495
555
  username: `user${overrides.userId ?? 1}`,
496
556
  isAdmin: overrides.isAdmin ?? false,
557
+ e2e: false,
558
+ suspended: false,
497
559
  created: 0
498
560
  }
499
561
  )
500
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
+ },
501
577
  ...overrides.deveye
502
578
  };
503
579
  const restrictions = new Map<string, ItemAccess>(
@@ -539,6 +615,7 @@ export function createTestContext<Repo = undefined>(
539
615
  quota: {
540
616
  ...pauses,
541
617
  limit: (key) => Promise.resolve(overrides.quotaLimits?.[key] ?? null),
618
+ paid: () => Promise.resolve(overrides.paid ?? true),
542
619
  // The exact rule of the app: never counted when unlimited, refused
543
620
  // once the count AFTER creation passes the limit.
544
621
  async assert(key, countAfter) {
@@ -552,6 +629,12 @@ export function createTestContext<Repo = undefined>(
552
629
  });
553
630
  }
554
631
  },
632
+ usage: usageIn(
633
+ overrides.quotas,
634
+ overrides.repo as Repo,
635
+ overrides.quotaLimits,
636
+ overrides.ownerWorkspaceIds ?? [workspaceId]
637
+ ),
555
638
  assertActive: (key, itemId) => assertActiveIn(pauses, key, itemId)
556
639
  },
557
640
  items: {
@@ -651,6 +734,8 @@ export interface RecordedServiceCalls extends RecordedCalls {
651
734
  liveChanges: number[];
652
735
  /** `live.changed` calls that named topics, as `{ workspaceId, topics }` (a bare beat is not listed here). */
653
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 }[];
654
739
  }
655
740
 
656
741
  export interface TestServiceDeps<Repo> extends FeatureServiceDeps<Repo> {
@@ -675,10 +760,20 @@ export interface TestServiceOverrides<Repo> {
675
760
  archives?: Readonly<Record<string, TestFolderArchive | Error>>;
676
761
  /** What `deps.access` answers. Default: every member holds every right. */
677
762
  access?: Partial<FeatureServiceDeps['access']>;
678
- /** The accounts `deps.accounts` knows. Default none. */
763
+ /** The accounts `deps.accounts` knows, and `deps.accountMail` writes to. Default none. */
679
764
  accounts?: readonly SdkAccount[];
765
+ /** What `deps.accountMail.configured` answers. Default true. */
766
+ mailConfigured?: boolean;
680
767
  /** The plan's limits `deps.quotaFor` applies, by YOUR quota key. Default none (unlimited). */
681
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[];
682
777
  /** The items the plan holds paused (`deps.pauses`), by YOUR `stock` quota key. Default none. */
683
778
  pausedItems?: Record<string, readonly string[]>;
684
779
  /** What `deveyeFor(...).notify.hasRoute` answers. Default true. */
@@ -716,7 +811,8 @@ export function createTestServiceDeps<Repo = undefined>(
716
811
  accountChanges: [],
717
812
  tickers: [],
718
813
  liveChanges: [],
719
- liveTopicChanges: []
814
+ liveTopicChanges: [],
815
+ mails: []
720
816
  };
721
817
  const stores = new Map<number, TestFeatureStore>();
722
818
  const sealedBytes = new Map<string, Uint8Array>();
@@ -728,6 +824,7 @@ export function createTestServiceDeps<Repo = undefined>(
728
824
  );
729
825
  const devices = recordingDevices(overrides.devices ?? []);
730
826
  const pauses = memoryPauses(overrides.pausedItems);
827
+ const objects = overrides.objects ?? memoryObjectStore();
731
828
  return {
732
829
  recorded,
733
830
  stores,
@@ -793,6 +890,7 @@ export function createTestServiceDeps<Repo = undefined>(
793
890
  quotaFor: () => ({
794
891
  ...pauses,
795
892
  limit: (key) => Promise.resolve(overrides.quotaLimits?.[key] ?? null),
893
+ paid: () => Promise.resolve(overrides.paid ?? true),
796
894
  async assert(key, countAfter) {
797
895
  const limit = overrides.quotaLimits?.[key];
798
896
  if (limit === undefined) return;
@@ -803,6 +901,12 @@ export function createTestServiceDeps<Repo = undefined>(
803
901
  });
804
902
  }
805
903
  },
904
+ usage: usageIn(
905
+ overrides.quotas,
906
+ overrides.repo as Repo,
907
+ overrides.quotaLimits,
908
+ overrides.workspaceIds ?? [1]
909
+ ),
806
910
  assertActive: (key, itemId) => assertActiveIn(pauses, key, itemId)
807
911
  }),
808
912
  pauses,
@@ -836,12 +940,45 @@ export function createTestServiceDeps<Repo = undefined>(
836
940
  return Promise.resolve(
837
941
  found.slice(0, Math.min(Math.max(1, Math.trunc(limit ?? 20)), 50))
838
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));
839
975
  }
840
976
  },
841
977
  audit: (entry) => {
842
978
  recorded.audits.push({ action: entry.action, description: entry.description });
843
979
  },
844
980
  agents: recordingAgents(recorded, overrides),
981
+ objects: () => objects,
845
982
  access: {
846
983
  feature: overrides.access?.feature ?? (() => Promise.resolve({ ok: true })),
847
984
  device: overrides.access?.device ?? (() => Promise.resolve({ ok: true }))
@@ -894,6 +1031,77 @@ export function testDomain(over: Partial<SdkDomain> & { id: number; host: string
894
1031
  };
895
1032
  }
896
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
+
897
1105
  /**
898
1106
  * What the `domains` hooks of a server entry receive, in memory: identity
899
1107
  * cipher, one store per workspace, and lookups that find nothing unless `dns`