@minca/core 0.1.7 → 0.1.9

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 (154) hide show
  1. package/dist/elements/auth-styles.d.ts +1 -1
  2. package/dist/elements/auth-styles.d.ts.map +1 -1
  3. package/dist/elements/auth-styles.js +16 -8
  4. package/dist/elements/auth-styles.js.map +1 -1
  5. package/dist/elements/minca-auth.d.ts +7 -0
  6. package/dist/elements/minca-auth.d.ts.map +1 -1
  7. package/dist/elements/minca-auth.js +107 -49
  8. package/dist/elements/minca-auth.js.map +1 -1
  9. package/dist/files/file-id.d.ts +51 -0
  10. package/dist/files/file-id.d.ts.map +1 -0
  11. package/dist/files/file-id.js +97 -0
  12. package/dist/files/file-id.js.map +1 -0
  13. package/dist/files/seal.d.ts +20 -0
  14. package/dist/files/seal.d.ts.map +1 -0
  15. package/dist/files/seal.js +77 -0
  16. package/dist/files/seal.js.map +1 -0
  17. package/dist/files/space-files.d.ts +51 -0
  18. package/dist/files/space-files.d.ts.map +1 -0
  19. package/dist/files/space-files.js +476 -0
  20. package/dist/files/space-files.js.map +1 -0
  21. package/dist/index.d.ts +5 -4
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +3 -2
  24. package/dist/index.js.map +1 -1
  25. package/dist/node/api.d.ts +6 -1
  26. package/dist/node/api.d.ts.map +1 -1
  27. package/dist/node/api.js +17 -3
  28. package/dist/node/api.js.map +1 -1
  29. package/dist/node/carrier.d.ts +17 -2
  30. package/dist/node/carrier.d.ts.map +1 -1
  31. package/dist/node/carrier.js +26 -4
  32. package/dist/node/carrier.js.map +1 -1
  33. package/dist/node/copy.d.ts +0 -4
  34. package/dist/node/copy.d.ts.map +1 -1
  35. package/dist/node/copy.js +26 -0
  36. package/dist/node/copy.js.map +1 -1
  37. package/dist/node/host.d.ts +66 -1
  38. package/dist/node/host.d.ts.map +1 -1
  39. package/dist/node/host.js +571 -5
  40. package/dist/node/host.js.map +1 -1
  41. package/dist/node/index.d.ts +2 -2
  42. package/dist/node/index.d.ts.map +1 -1
  43. package/dist/node/index.js +1 -1
  44. package/dist/node/index.js.map +1 -1
  45. package/dist/node/node.d.ts.map +1 -1
  46. package/dist/node/node.js +235 -75
  47. package/dist/node/node.js.map +1 -1
  48. package/dist/node/space-runtime.d.ts +9 -0
  49. package/dist/node/space-runtime.d.ts.map +1 -1
  50. package/dist/node/space-runtime.js +125 -16
  51. package/dist/node/space-runtime.js.map +1 -1
  52. package/dist/node/stores.d.ts +44 -8
  53. package/dist/node/stores.d.ts.map +1 -1
  54. package/dist/node/stores.js +44 -7
  55. package/dist/node/stores.js.map +1 -1
  56. package/dist/node/types.d.ts +73 -6
  57. package/dist/node/types.d.ts.map +1 -1
  58. package/dist/node/usage.d.ts +54 -0
  59. package/dist/node/usage.d.ts.map +1 -0
  60. package/dist/node/usage.js +201 -0
  61. package/dist/node/usage.js.map +1 -0
  62. package/dist/node/writer-keys.d.ts +4 -1
  63. package/dist/node/writer-keys.d.ts.map +1 -1
  64. package/dist/node/writer-keys.js +25 -6
  65. package/dist/node/writer-keys.js.map +1 -1
  66. package/dist/node/writers.d.ts.map +1 -1
  67. package/dist/node/writers.js +10 -3
  68. package/dist/node/writers.js.map +1 -1
  69. package/dist/react/minca-auth.d.ts +3 -1
  70. package/dist/react/minca-auth.d.ts.map +1 -1
  71. package/dist/react/minca-auth.js +5 -3
  72. package/dist/react/minca-auth.js.map +1 -1
  73. package/dist/schema/version.d.ts +5 -0
  74. package/dist/schema/version.d.ts.map +1 -1
  75. package/dist/schema/version.js +1 -0
  76. package/dist/schema/version.js.map +1 -1
  77. package/dist/schemas/fragments.d.ts +23 -2
  78. package/dist/schemas/fragments.d.ts.map +1 -1
  79. package/dist/schemas/fragments.js +5 -2
  80. package/dist/schemas/fragments.js.map +1 -1
  81. package/dist/schemas/library/annotations.d.ts +24 -0
  82. package/dist/schemas/library/annotations.d.ts.map +1 -1
  83. package/dist/schemas/library/community.d.ts +24 -0
  84. package/dist/schemas/library/community.d.ts.map +1 -1
  85. package/dist/schemas/library/life.d.ts +72 -0
  86. package/dist/schemas/library/life.d.ts.map +1 -1
  87. package/dist/schemas/library/media.d.ts +144 -0
  88. package/dist/schemas/library/media.d.ts.map +1 -1
  89. package/dist/schemas/library/money.d.ts +24 -0
  90. package/dist/schemas/library/money.d.ts.map +1 -1
  91. package/dist/schemas/library/publishing.d.ts +96 -0
  92. package/dist/schemas/library/publishing.d.ts.map +1 -1
  93. package/dist/schemas/library/social.d.ts +72 -0
  94. package/dist/schemas/library/social.d.ts.map +1 -1
  95. package/dist/session/account-hint.d.ts +13 -0
  96. package/dist/session/account-hint.d.ts.map +1 -0
  97. package/dist/session/account-hint.js +51 -0
  98. package/dist/session/account-hint.js.map +1 -0
  99. package/dist/session/auth.d.ts +51 -3
  100. package/dist/session/auth.d.ts.map +1 -1
  101. package/dist/session/auth.js +262 -36
  102. package/dist/session/auth.js.map +1 -1
  103. package/dist/session/connect.d.ts.map +1 -1
  104. package/dist/session/connect.js +6 -2
  105. package/dist/session/connect.js.map +1 -1
  106. package/dist/session/hosting.d.ts +73 -28
  107. package/dist/session/hosting.d.ts.map +1 -1
  108. package/dist/session/hosting.js +85 -5
  109. package/dist/session/hosting.js.map +1 -1
  110. package/dist/session/index.d.ts +1 -0
  111. package/dist/session/index.d.ts.map +1 -1
  112. package/dist/session/index.js +1 -0
  113. package/dist/session/index.js.map +1 -1
  114. package/dist/session/pairing.d.ts +2 -0
  115. package/dist/session/pairing.d.ts.map +1 -1
  116. package/dist/session/pairing.js +8 -0
  117. package/dist/session/pairing.js.map +1 -1
  118. package/dist/session/places.d.ts +7 -0
  119. package/dist/session/places.d.ts.map +1 -1
  120. package/dist/session/places.js +20 -2
  121. package/dist/session/places.js.map +1 -1
  122. package/dist/space/account-registry.d.ts +13 -0
  123. package/dist/space/account-registry.d.ts.map +1 -1
  124. package/dist/space/account-registry.js +13 -0
  125. package/dist/space/account-registry.js.map +1 -1
  126. package/dist/storage/blob/directory.d.ts +14 -0
  127. package/dist/storage/blob/directory.d.ts.map +1 -0
  128. package/dist/storage/blob/directory.js +80 -0
  129. package/dist/storage/blob/directory.js.map +1 -0
  130. package/dist/storage/folder-adapter.d.ts +22 -0
  131. package/dist/storage/folder-adapter.d.ts.map +1 -1
  132. package/dist/storage/folder-adapter.js +5 -5
  133. package/dist/storage/folder-adapter.js.map +1 -1
  134. package/dist/storage/mirror.d.ts +9 -2
  135. package/dist/storage/mirror.d.ts.map +1 -1
  136. package/dist/storage/mirror.js +60 -35
  137. package/dist/storage/mirror.js.map +1 -1
  138. package/dist/storage/segment.d.ts +7 -2
  139. package/dist/storage/segment.d.ts.map +1 -1
  140. package/dist/storage/segment.js +25 -3
  141. package/dist/storage/segment.js.map +1 -1
  142. package/dist/sync/sync-engine.d.ts +2 -0
  143. package/dist/sync/sync-engine.d.ts.map +1 -1
  144. package/dist/sync/sync-engine.js +5 -0
  145. package/dist/sync/sync-engine.js.map +1 -1
  146. package/dist/sync/sync-messages.d.ts +24 -0
  147. package/dist/sync/sync-messages.d.ts.map +1 -1
  148. package/dist/sync/sync-messages.js.map +1 -1
  149. package/docs/node.md +63 -24
  150. package/docs/sign-in.md +123 -24
  151. package/docs/spaces.md +18 -10
  152. package/docs/standard-library.md +16 -20
  153. package/docs/storage.md +120 -15
  154. package/package.json +1 -1
package/dist/node/host.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { createUsageMeter } from './usage.js';
1
2
  import { createP256Provider } from '../identity/crypto-p256.js';
2
3
  import { createServerAuth } from '../network/peer-auth.js';
3
4
  import { utf8Decode, utf8Encode } from '../utils/encoding.js';
@@ -5,6 +6,7 @@ import { isRecord } from '../utils/guards.js';
5
6
  import { createCarryCore } from './carrier.js';
6
7
  import { deleteMirrored } from '../storage/mirror.js';
7
8
  import { openPass } from '../space/pass.js';
9
+ import { parseSpaceInvite } from '../space/space-manager.js';
8
10
  import { createListeners } from '../utils/events.js';
9
11
  /** What names a space's own subscription at a host */
10
12
  const SPACE_SUBSCRIPTION_PREFIX = 'space:';
@@ -23,7 +25,19 @@ export class NotAllowedError extends Error {
23
25
  }
24
26
  /** Where the subscriptions are kept in the bucket */
25
27
  const BUCKET_PREFIX = 'host/subscriptions/';
28
+ /** Where each space's standing against the free line is kept, there and in the bucket */
29
+ const LINE_PREFIX = 'line:';
30
+ const LINE_BUCKET_PREFIX = 'host/lines/';
26
31
  const DAY = 24 * 3600;
32
+ /** How far under every limit a space must stay, for its window, to be free again */
33
+ const UNDER = 0.8;
34
+ /** How long after the host first sees a space what arrives may be its history, rather than people writing now */
35
+ const CATCH_UP_SECONDS = 600;
36
+ /** Where the host keeps which spaces it once stopped carrying for members, there and in the bucket */
37
+ const STRUCK_PREFIX = 'struck:';
38
+ /** Days of notice a space gets when it goes over again after its grace was spent, before it is stopped */
39
+ const NOTICE_DAYS = 7;
40
+ const STRUCK_BUCKET_PREFIX = 'host/struck/';
27
41
  /** Starts a host */
28
42
  export async function createHostNode(config) {
29
43
  const provider = config.provider ?? createP256Provider();
@@ -54,11 +68,199 @@ export async function createHostNode(config) {
54
68
  const keys = await store.list(SUBSCRIPTION_PREFIX);
55
69
  return (await Promise.all(keys.map((key) => read(key.slice(SUBSCRIPTION_PREFIX.length))))).filter((s) => s !== null);
56
70
  };
71
+ const limits = config.free ? null : (config.limits ?? null);
57
72
  const state = (subscription) => {
58
73
  if (config.free || subscription.paidUntil >= now())
59
74
  return 'active';
75
+ // With limits an account needs no payment: not paying is the free plan.
76
+ if (limits && !spaceIdOf(subscription.id))
77
+ return 'active';
60
78
  return subscription.paidUntil + graceSeconds >= now() ? 'grace' : 'lapsed';
61
79
  };
80
+ /** Which room an account's subscription has, at a host with limits; null otherwise */
81
+ const plan = (subscription) => limits && !spaceIdOf(subscription.id) ? (subscription.paidUntil >= now() ? 'paid' : 'free') : null;
82
+ // ─── The free line ─────────────────────────────────────────────────
83
+ const meter = limits
84
+ ? await createUsageMeter({
85
+ store: await config.stores('host-usage'),
86
+ windowDays: limits.space.windowDays,
87
+ now,
88
+ })
89
+ : null;
90
+ const lines = new Map();
91
+ const lineBucketKey = (spaceId) => `${LINE_BUCKET_PREFIX}${spaceId}.json`;
92
+ const writeLine = async (spaceId, line) => {
93
+ if (line)
94
+ lines.set(spaceId, line);
95
+ else
96
+ lines.delete(spaceId);
97
+ if (line) {
98
+ const bytes = utf8Encode(JSON.stringify(line));
99
+ await store.put(`${LINE_PREFIX}${spaceId}`, bytes);
100
+ // A restart, or a new disk, keeps the grace clock where it was.
101
+ await config.mirror?.put(lineBucketKey(spaceId), bytes);
102
+ }
103
+ else {
104
+ await store.delete(`${LINE_PREFIX}${spaceId}`);
105
+ await config.mirror?.delete(lineBucketKey(spaceId));
106
+ }
107
+ };
108
+ if (limits) {
109
+ if (config.mirror && (await store.list(LINE_PREFIX)).length === 0)
110
+ for (const key of await config.mirror.list(LINE_BUCKET_PREFIX)) {
111
+ const bytes = await config.mirror.get(key);
112
+ const spaceId = key.slice(LINE_BUCKET_PREFIX.length, -'.json'.length);
113
+ if (bytes && spaceId)
114
+ await store.put(`${LINE_PREFIX}${spaceId}`, bytes);
115
+ }
116
+ for (const key of await store.list(LINE_PREFIX)) {
117
+ const bytes = await store.get(key);
118
+ const line = bytes ? JSON.parse(utf8Decode(bytes)) : null;
119
+ if (isRecord(line) &&
120
+ typeof line.since === 'number' &&
121
+ typeof line.from === 'number' &&
122
+ Array.isArray(line.reasons))
123
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- this host's own writes, shape checked
124
+ lines.set(key.slice(LINE_PREFIX.length), line);
125
+ }
126
+ }
127
+ const lineGrace = (limits?.graceDays ?? 0) * DAY;
128
+ /** Each account over its room, there and in the bucket */
129
+ const ROOM_PREFIX = 'room:';
130
+ const ROOM_BUCKET_PREFIX = 'host/rooms/';
131
+ const rooms = new Map();
132
+ if (limits) {
133
+ if (config.mirror && (await store.list(ROOM_PREFIX)).length === 0)
134
+ for (const key of await config.mirror.list(ROOM_BUCKET_PREFIX)) {
135
+ const bytes = await config.mirror.get(key);
136
+ // Named in the bucket by the account DID, encoded: the store by the DID itself.
137
+ if (bytes)
138
+ await store.put(`${ROOM_PREFIX}${decodeURIComponent(key.slice(ROOM_BUCKET_PREFIX.length))}`, bytes);
139
+ }
140
+ for (const key of await store.list(ROOM_PREFIX)) {
141
+ const bytes = await store.get(key);
142
+ const room = bytes ? JSON.parse(utf8Decode(bytes)) : null;
143
+ if (isRecord(room) && typeof room.full === 'number') {
144
+ const held = {};
145
+ if (isRecord(room.held))
146
+ for (const [spaceId, since] of Object.entries(room.held))
147
+ if (typeof since === 'number')
148
+ held[spaceId] = since;
149
+ rooms.set(key.slice(ROOM_PREFIX.length), {
150
+ full: room.full,
151
+ ...(typeof room.fits === 'number' ? { fits: room.fits } : {}),
152
+ ...(room.refused === true ? { refused: true } : {}),
153
+ ...(Object.keys(held).length ? { held } : {}),
154
+ });
155
+ }
156
+ }
157
+ }
158
+ const writeRoom = async (account, room) => {
159
+ if (JSON.stringify(room) === JSON.stringify(rooms.get(account) ?? null))
160
+ return;
161
+ const key = encodeURIComponent(account);
162
+ if (room) {
163
+ rooms.set(account, room);
164
+ const bytes = utf8Encode(JSON.stringify(room));
165
+ await store.put(`${ROOM_PREFIX}${account}`, bytes);
166
+ await config.mirror?.put(`${ROOM_BUCKET_PREFIX}${key}`, bytes);
167
+ }
168
+ else {
169
+ rooms.delete(account);
170
+ await store.delete(`${ROOM_PREFIX}${account}`);
171
+ await config.mirror?.delete(`${ROOM_BUCKET_PREFIX}${key}`);
172
+ }
173
+ };
174
+ /** The account a subscription carries for */
175
+ const accountOf = (subscription) => subscription.carry?.account;
176
+ /** Whether a subscription's account is past its notice of being over its room */
177
+ const outOfRoom = (subscription) => {
178
+ const room = rooms.get(accountOf(subscription) ?? '');
179
+ return room !== undefined && room.full + lineGrace <= now();
180
+ };
181
+ /** Each carry space's spaces held back for want of its room, and all of them together */
182
+ const holds = new Map();
183
+ /** Those whose copy the host still keeps: held back less than `keepDays` for some account */
184
+ const roomHeld = new Set();
185
+ /** Held back longer, their copy already deleted: not deleted again until the host restarts */
186
+ const dropped = new Set();
187
+ /** Spaces members' subscriptions no longer carry, being over the line with nobody paying */
188
+ const skipped = new Set([...lines].flatMap(([spaceId, line]) => (line.stopped !== undefined ? [spaceId] : [])));
189
+ /**
190
+ * Spaces members' subscriptions once stopped carrying, and when: one that
191
+ * comes back over the line after the host forgot it gets no new grace.
192
+ */
193
+ const struck = new Map();
194
+ const strike = async (spaceId, at) => {
195
+ struck.set(spaceId, at);
196
+ const bytes = utf8Encode(String(at));
197
+ await store.put(`${STRUCK_PREFIX}${spaceId}`, bytes);
198
+ await config.mirror?.put(`${STRUCK_BUCKET_PREFIX}${spaceId}`, bytes);
199
+ };
200
+ const unstrike = async (spaceId) => {
201
+ if (!struck.delete(spaceId))
202
+ return;
203
+ await store.delete(`${STRUCK_PREFIX}${spaceId}`);
204
+ await config.mirror?.delete(`${STRUCK_BUCKET_PREFIX}${spaceId}`);
205
+ };
206
+ if (limits) {
207
+ if (config.mirror && (await store.list(STRUCK_PREFIX)).length === 0)
208
+ for (const key of await config.mirror.list(STRUCK_BUCKET_PREFIX)) {
209
+ const bytes = await config.mirror.get(key);
210
+ if (bytes)
211
+ await store.put(`${STRUCK_PREFIX}${key.slice(STRUCK_BUCKET_PREFIX.length)}`, bytes);
212
+ }
213
+ for (const key of await store.list(STRUCK_PREFIX)) {
214
+ const bytes = await store.get(key);
215
+ const at = bytes ? Number(utf8Decode(bytes)) : NaN;
216
+ if (Number.isFinite(at))
217
+ struck.set(key.slice(STRUCK_PREFIX.length), at);
218
+ }
219
+ }
220
+ /**
221
+ * A version reached a carried space: its account wrote there, unless it is
222
+ * the host's own. Counted by when it arrived, whatever its writer says of
223
+ * when it was written, except while the host first catches up on a space:
224
+ * then what says it is older than the window is its history.
225
+ */
226
+ const counted = (spaceId, version) => {
227
+ if (!meter || !limits)
228
+ return;
229
+ const account = version.proof?.payload.iss ?? version.author;
230
+ const written = Date.parse(version.createdAt) / 1000;
231
+ const old = Number.isFinite(written) && written < now() - limits.space.windowDays * DAY;
232
+ void (async () => {
233
+ const first = await meter.firstSeen(spaceId);
234
+ if (old && now() - first < CATCH_UP_SECONDS)
235
+ return;
236
+ if (!(await config.ignore?.(account)))
237
+ await meter.wrote(spaceId, account);
238
+ })().catch(() => { });
239
+ };
240
+ /** Whether anyone but the account holds a role in its carry space: then it is a shared space */
241
+ const sharedCarry = async (carrySpace, account) => {
242
+ const entry = core.carried.get(carrySpace);
243
+ if (!entry)
244
+ return false;
245
+ return (await entry.runtime.access()).members.some((member) => member.did !== account && (member.founder || member.roles.length > 0));
246
+ };
247
+ /** Stops a carry space being any subscription's */
248
+ const letCarryGo = async (carrySpace) => {
249
+ for (const subscription of await list()) {
250
+ if (subscription.carry?.space !== carrySpace)
251
+ continue;
252
+ const { carry: _gone, ...rest } = subscription;
253
+ await write(rest);
254
+ }
255
+ await core.removeCarry(carrySpace);
256
+ };
257
+ /** The accounts that are members of a carried space now: only their writes count */
258
+ const membersOf = async (spaceId) => {
259
+ const entry = core.carried.get(spaceId);
260
+ if (!entry)
261
+ return undefined;
262
+ return (await entry.runtime.access()).members.map((member) => member.did);
263
+ };
62
264
  // A fresh disk: the subscriptions come back from the bucket, and the spaces with them.
63
265
  if (config.mirror && (await store.list(SUBSCRIPTION_PREFIX)).length === 0) {
64
266
  for (const key of await config.mirror.list(BUCKET_PREFIX)) {
@@ -72,16 +274,39 @@ export async function createHostNode(config) {
72
274
  }
73
275
  /** The subscription an account's carry space belongs to, when it wrote `carry:closed` */
74
276
  let closing = Promise.resolve();
277
+ /** Whether the carry core below is made, so its events may look at it */
278
+ let opened = false;
75
279
  const core = await createCarryCore({
76
280
  key: config.key,
77
281
  stores: config.stores,
78
282
  ...(config.network ? { network: config.network } : {}),
79
283
  provider,
80
284
  ...(config.watchIntervalMs !== undefined ? { watchIntervalMs: config.watchIntervalMs } : {}),
81
- emit: events.emit,
285
+ emit: (event) => {
286
+ // A space newly carried: what arrives over the next minutes is it catching up.
287
+ if (event.type === 'spaces' && meter && opened)
288
+ for (const spaceId of core.carried.keys())
289
+ void meter.firstSeen(spaceId).catch(() => { });
290
+ events.emit(event);
291
+ },
82
292
  ...(config.full ? { full: config.full } : {}),
293
+ ...(limits
294
+ ? {
295
+ skip: (spaceId) => skipped.has(spaceId),
296
+ held: (carrySpace) => holds.get(carrySpace),
297
+ onArrived: counted,
298
+ }
299
+ : {}),
300
+ ...(config.spacesPerCarry !== undefined ? { most: config.spacesPerCarry } : {}),
83
301
  ...(config.mirror
84
- ? { mirror: config.mirror, onRelease: (spaceId) => deleteMirrored(config.mirror, spaceId) }
302
+ ? {
303
+ mirror: config.mirror,
304
+ // One stopped for being over the line is kept a while, so a fund brings it back as it was.
305
+ onRelease: async (spaceId) => {
306
+ if (!skipped.has(spaceId) && !roomHeld.has(spaceId))
307
+ await deleteMirrored(config.mirror, spaceId);
308
+ },
309
+ }
85
310
  : {}),
86
311
  onClosed: (carrySpace) => {
87
312
  // The account stopped using this host: forget its carry space; the subscription stays paid.
@@ -96,6 +321,7 @@ export async function createHostNode(config) {
96
321
  });
97
322
  },
98
323
  });
324
+ opened = true;
99
325
  // Carry again what was carried before a restart — the store is only a cache of the spaces, but the list is ours.
100
326
  for (const subscription of await list()) {
101
327
  if (subscription.pass !== undefined && state(subscription) !== 'lapsed') {
@@ -113,6 +339,166 @@ export async function createHostNode(config) {
113
339
  }
114
340
  /** Whether another subscription still carries this carry space */
115
341
  const carriedByOther = async (carrySpace, except) => (await list()).some((other) => other.id !== except && other.carry?.space === carrySpace);
342
+ /** Whether a space's own subscription pays for it now, within the room its fund buys: the free line does not apply then */
343
+ const paysItself = async (spaceId) => {
344
+ const own = await read(`${SPACE_SUBSCRIPTION_PREFIX}${spaceId}`);
345
+ return !!own && state(own) === 'active';
346
+ };
347
+ /** The spaces the free line is about: those accounts' passes name, and those carried for themselves; never a carry space */
348
+ const metered = () => {
349
+ const found = new Set();
350
+ for (const entry of core.carries.values())
351
+ for (const spaceId of entry.named)
352
+ found.add(spaceId);
353
+ // Carry spaces too: an account's own has one writer, and a shared space handed over as one is held to the line.
354
+ for (const spaceId of core.carried.keys())
355
+ found.add(spaceId);
356
+ return found;
357
+ };
358
+ /** Where one space stands now: its counts, its size, and the line it is held to */
359
+ async function standing(spaceId, before, own) {
360
+ if (!limits || !meter)
361
+ return null;
362
+ const t = now();
363
+ const window = limits.space.windowDays * DAY;
364
+ const keep = (limits.keepDays ?? 0) * DAY;
365
+ // Members stopped carrying it, so nothing it does reaches here: it stays as it was, and is forgotten after a while.
366
+ if (before?.stopped !== undefined && !own)
367
+ return before.stopped + keep <= t ? null : before;
368
+ // Not carried now, so who is a member can't be read: judged again once it is, as it was till then.
369
+ const members = await membersOf(spaceId);
370
+ if (!members)
371
+ return before ?? null;
372
+ const counts = await meter.usage(spaceId, members);
373
+ const bytes = (await config.measure?.(spaceId).catch(() => 0)) ?? 0;
374
+ const shared = counts.writers >= 2;
375
+ // One writer is never a community, whatever the limit says.
376
+ const most = Math.max(limits.space.writers, 1);
377
+ const reasons = [];
378
+ if (counts.writers > most)
379
+ reasons.push('writers');
380
+ if (shared && bytes > limits.space.bytes)
381
+ reasons.push('bytes');
382
+ const wellUnder = counts.writers <= most * UNDER && (!shared || bytes <= limits.space.bytes * UNDER);
383
+ let line = before ?? null;
384
+ // Its grace was spent once, by a stop or by running out while it was under: over again,
385
+ // it gets only a short notice, never a whole grace again.
386
+ const notice = t - lineGrace + NOTICE_DAYS * DAY;
387
+ const spent = before ? before.calm === true && before.from + lineGrace <= t : struck.has(spaceId);
388
+ if (reasons.length > 0) {
389
+ const from = spent ? Math.max(before?.from ?? notice, notice) : (before?.from ?? t);
390
+ line = { since: before?.since ?? t, from, reasons, lastOver: t };
391
+ }
392
+ else if (line && wellUnder) {
393
+ const under = line.under ?? t;
394
+ // Free again only after a whole window well under, so a busy week does not flip it.
395
+ if (t - under >= window)
396
+ return null;
397
+ line = { ...line, calm: true, under };
398
+ }
399
+ else if (line) {
400
+ const { under: _gone, ...rest } = line;
401
+ line = { ...rest, calm: true };
402
+ }
403
+ if (!line)
404
+ return null;
405
+ // While it pays for itself the line does not apply. Its grace is given once: paying for
406
+ // a while does not buy it again, so once the fund stops, what is left of it is all it has.
407
+ if (own) {
408
+ const { stopped: _paid, ...rest } = line;
409
+ return rest;
410
+ }
411
+ // Stopped once its grace runs out if it is over then, or was at any look in the last days
412
+ // before: one that went back under in time keeps its notice and is carried, but going
413
+ // under for an hour as the date passes buys nothing.
414
+ const until = line.from + lineGrace;
415
+ const lately = (line.lastOver ?? 0) >= until - NOTICE_DAYS * DAY;
416
+ return (reasons.length > 0 || lately) && until <= t && line.stopped === undefined
417
+ ? { ...line, stopped: t }
418
+ : line;
419
+ }
420
+ /**
421
+ * Each space against the free line, and members' subscriptions let go of
422
+ * those past it. Run now and then. Says which spaces went over, stopped
423
+ * being carried for members, or came back under.
424
+ */
425
+ async function evaluate() {
426
+ const changed = {
427
+ over: [],
428
+ stopped: [],
429
+ under: [],
430
+ };
431
+ if (!limits || !meter)
432
+ return changed;
433
+ await meter.prune();
434
+ const spaces = metered();
435
+ for (const spaceId of new Set([...spaces, ...lines.keys()]))
436
+ await evaluateOne(spaceId, spaces, changed).catch((error) => {
437
+ // One space that can't be judged now is judged next time; the others go on.
438
+ console.error(`Could not hold space ${spaceId} to the free line:`, error);
439
+ });
440
+ await core.refresh();
441
+ return changed;
442
+ }
443
+ async function evaluateOne(spaceId, spaces, changed) {
444
+ if (!meter)
445
+ return;
446
+ {
447
+ const before = lines.get(spaceId);
448
+ const own = await paysItself(spaceId);
449
+ // A space nobody names for a while keeps its line: the line goes only by a whole window
450
+ // under, or after a stop, by `keepDays`; never because it was let go for an hour.
451
+ const after = spaces.has(spaceId) || before ? await standing(spaceId, before, own) : null;
452
+ // A stop long forgotten, and a window more under: its grace is its own again.
453
+ const struckAt = struck.get(spaceId);
454
+ if (!before && !after && struckAt !== undefined && limits) {
455
+ const forgotten = ((limits.keepDays ?? 0) + limits.space.windowDays) * DAY;
456
+ if (struckAt + forgotten <= now())
457
+ await unstrike(spaceId);
458
+ }
459
+ if (JSON.stringify(after) !== JSON.stringify(before ?? null))
460
+ await writeLine(spaceId, after);
461
+ if (after && !before)
462
+ changed.over.push(spaceId);
463
+ if (after?.stopped !== undefined && before?.stopped === undefined) {
464
+ changed.stopped.push(spaceId);
465
+ await strike(spaceId, after.stopped);
466
+ // A shared space handed over as someone's carry space: it stops being theirs to carry.
467
+ // Skipped first, so letting it go keeps the bucket's copy.
468
+ skipped.add(spaceId);
469
+ if (core.carries.has(spaceId))
470
+ await letCarryGo(spaceId);
471
+ }
472
+ // A carry space someone else came to hold a role in is let go: it is a shared space.
473
+ const account = core.carries.get(spaceId)?.account;
474
+ if (account && (await sharedCarry(spaceId, account)))
475
+ await letCarryGo(spaceId);
476
+ if (before && !after)
477
+ changed.under.push(spaceId);
478
+ // Free again after a whole window well under: its grace is its own again.
479
+ if (before && !after && before.stopped === undefined)
480
+ await unstrike(spaceId);
481
+ const skip = after?.stopped !== undefined && !own;
482
+ if (skip)
483
+ skipped.add(spaceId);
484
+ else
485
+ skipped.delete(spaceId);
486
+ // Forgotten after it was kept a while: what the host held of it goes too, unless something carries it.
487
+ if (before?.stopped !== undefined && !after) {
488
+ await meter.forget(spaceId);
489
+ if (config.mirror && !core.carried.has(spaceId))
490
+ await deleteMirrored(config.mirror, spaceId).catch(() => { });
491
+ }
492
+ }
493
+ }
494
+ /** The spaces over the line among these, as a status says them */
495
+ const overOf = (spaceIds) => [...spaceIds].flatMap((spaceId) => {
496
+ const line = lines.get(spaceId);
497
+ // One back under and carried is not over: it keeps its line, quietly, until free again.
498
+ return line && (!line.calm || line.stopped !== undefined)
499
+ ? [{ space: spaceId, since: line.since, until: line.from + lineGrace, reasons: line.reasons }]
500
+ : [];
501
+ });
116
502
  /** Makes a subscription if there is none by this id, and returns it */
117
503
  const subscribe = async (id) => {
118
504
  if (!id.startsWith('did:key:') && !spaceIdOf(id))
@@ -126,6 +512,150 @@ export async function createHostNode(config) {
126
512
  list,
127
513
  /** Whether a subscription is paid, in its grace period, or lapsed */
128
514
  state,
515
+ /** At a host with limits, which room an account's subscription has: null at one without */
516
+ plan,
517
+ /** The limits it keeps to, or null when it has none */
518
+ limits,
519
+ /**
520
+ * Whether a subscription's spaces take more than its room, as its host
521
+ * measured. The notice runs from when they first did, and goes only after
522
+ * a whole window of fitting, so a dip under for an hour starts nothing anew.
523
+ */
524
+ async setFull(id, over) {
525
+ const subscription = await read(id);
526
+ const account = subscription && accountOf(subscription);
527
+ if (!account || !limits)
528
+ return;
529
+ const room = rooms.get(account);
530
+ const t = now();
531
+ if (over)
532
+ await writeRoom(account, {
533
+ full: room?.full ?? t,
534
+ ...(room?.refused ? { refused: true } : {}),
535
+ ...(room?.held ? { held: room.held } : {}),
536
+ });
537
+ else if (room) {
538
+ const fits = room.fits ?? t;
539
+ // Fitting a whole window: the notice goes, though a refusal stays until the host's owner says.
540
+ if (t - fits >= limits.space.windowDays * DAY && !room.refused)
541
+ await writeRoom(account, null);
542
+ else
543
+ await writeRoom(account, { ...room, fits });
544
+ }
545
+ },
546
+ /** Whether a subscription is past its notice of being over its room */
547
+ outOfRoom,
548
+ /**
549
+ * Holds back these solo spaces of a subscription's for want of room, and
550
+ * no others of its: the host keeps them, unserved, until they fit.
551
+ */
552
+ async holdForRoom(id, spaceIds) {
553
+ const subscription = await read(id);
554
+ const carrySpace = subscription?.carry?.space;
555
+ const account = subscription && accountOf(subscription);
556
+ if (!carrySpace || !account)
557
+ return;
558
+ const t = now();
559
+ const room = rooms.get(account);
560
+ if (room) {
561
+ const { held: before = {}, ...rest } = room;
562
+ const held = Object.fromEntries(spaceIds.map((spaceId) => [spaceId, before[spaceId] ?? t]));
563
+ await writeRoom(account, Object.keys(held).length ? { ...rest, held } : rest);
564
+ }
565
+ const before = [...holds]
566
+ .map(([space, held]) => `${space}:${[...held].sort().join(',')}`)
567
+ .sort()
568
+ .join(' ');
569
+ if (spaceIds.length)
570
+ holds.set(carrySpace, new Set(spaceIds));
571
+ else
572
+ holds.delete(carrySpace);
573
+ roomHeld.clear();
574
+ const keep = (limits?.keepDays ?? 0) * DAY;
575
+ for (const one of rooms.values())
576
+ for (const [spaceId, since] of Object.entries(one.held ?? {}))
577
+ if (since + keep > t)
578
+ roomHeld.add(spaceId);
579
+ // Held back longer than that for every account that holds it: the host's copy goes, as for a stop.
580
+ for (const held of holds.values())
581
+ for (const spaceId of held) {
582
+ if (roomHeld.has(spaceId) ||
583
+ dropped.has(spaceId) ||
584
+ skipped.has(spaceId) ||
585
+ core.carried.has(spaceId))
586
+ continue;
587
+ dropped.add(spaceId);
588
+ if (config.mirror)
589
+ await deleteMirrored(config.mirror, spaceId).catch(() => { });
590
+ }
591
+ // Carried again, by room made or someone else: should it be held that long again, its copy goes again.
592
+ for (const spaceId of dropped)
593
+ if (core.carried.has(spaceId))
594
+ dropped.delete(spaceId);
595
+ const after = [...holds]
596
+ .map(([space, held]) => `${space}:${[...held].sort().join(',')}`)
597
+ .sort()
598
+ .join(' ');
599
+ if (after !== before)
600
+ await core.refresh();
601
+ },
602
+ /**
603
+ * Stops carrying a subscription's carry space, which is over its room by
604
+ * itself past its notice, and turns it away until the host's owner says.
605
+ */
606
+ async refuse(id) {
607
+ const subscription = await read(id);
608
+ if (!subscription?.carry)
609
+ return;
610
+ const { carry, ...rest } = subscription;
611
+ await writeRoom(carry.account, { ...(rooms.get(carry.account) ?? { full: now() }), refused: true });
612
+ await write(rest);
613
+ if (!(await carriedByOther(carry.space, id)))
614
+ await core.removeCarry(carry.space);
615
+ },
616
+ async seen(id) {
617
+ const subscription = await read(id);
618
+ if (!subscription || (subscription.seen !== undefined && now() - subscription.seen < DAY))
619
+ return;
620
+ await write({ ...subscription, seen: now() });
621
+ },
622
+ /** A session key proved it reads a carried space: counted, though readers only ever hint */
623
+ read(spaceId, session) {
624
+ if (core.carried.has(spaceId))
625
+ meter?.read(spaceId, session);
626
+ },
627
+ evaluate,
628
+ /** The spaces over the free line that a subscription names, or its own space when it is one */
629
+ async overFor(id) {
630
+ const own = spaceIdOf(id);
631
+ if (own)
632
+ return overOf([own]);
633
+ const space = (await read(id))?.carry?.space;
634
+ const named = space ? [space, ...(core.carries.get(space)?.named ?? [])] : [];
635
+ // One its own fund pays for is nothing its members need to hear about.
636
+ const unpaid = [];
637
+ for (const spaceId of named)
638
+ if (lines.has(spaceId) && !(await paysItself(spaceId)))
639
+ unpaid.push(spaceId);
640
+ return overOf(unpaid);
641
+ },
642
+ /** How a space is used, as a status says it; null at a host without limits */
643
+ async usage(spaceId) {
644
+ if (!meter)
645
+ return null;
646
+ const counts = await meter.usage(spaceId, await membersOf(spaceId));
647
+ const bytes = core.carried.has(spaceId) ? ((await config.measure?.(spaceId).catch(() => 0)) ?? 0) : 0;
648
+ return { writers: counts.writers, readers: counts.readers, bytes, windowDays: counts.windowDays };
649
+ },
650
+ /** When a subscription's notice of being over its room runs out, or null when it is not over */
651
+ fullUntil: (subscription) => {
652
+ const room = rooms.get(accountOf(subscription) ?? '');
653
+ return room ? { since: room.full, until: room.full + lineGrace } : null;
654
+ },
655
+ /** Whether members' subscriptions hold a space back, being past the free line: no member's room counts it */
656
+ heldBack: (spaceId) => skipped.has(spaceId),
657
+ /** Whether a space pays for itself now, so no account's room counts it */
658
+ paysItself,
129
659
  /** Moves a subscription's paid-until date — the one thing payments do */
130
660
  async extend(id, until, customer) {
131
661
  const subscription = await subscribe(id);
@@ -173,7 +703,33 @@ export async function createHostNode(config) {
173
703
  throw new Error('An account is named by its DID');
174
704
  if (!allowed(account))
175
705
  throw new NotAllowedError();
706
+ // Kept by the account, so a new subscription key brings nothing back; paying does, as a balance has no room.
707
+ const room = rooms.get(account);
708
+ if (room?.refused && plan(subscription) !== 'paid')
709
+ throw new Error('This host stopped carrying for this account: its carry space was over its room');
710
+ if (room?.refused) {
711
+ const { refused: _lifted, ...rest } = room;
712
+ await writeRoom(account, rest);
713
+ }
714
+ // A shared space stopped for being over the line comes back only through its own fund.
715
+ const asked = parseSpaceInvite(invite).space.id;
716
+ if (lines.get(asked)?.stopped !== undefined && !(await paysItself(asked)))
717
+ throw new Error('That space is over this host’s free line: only its own fund carries it');
718
+ // One carried, or named, for others already is theirs to carry: taking it as a carry space
719
+ // would take it from them, and letting it go again would drop the host's copy.
720
+ if (limits && !core.carries.has(asked)) {
721
+ const others = core.carried.has(asked) || [...core.carries.values()].some((entry) => entry.named.has(asked));
722
+ if (others)
723
+ throw new Error('That is a space others are members of, not a carry space');
724
+ }
176
725
  const space = await core.addCarry(account, invite);
726
+ // A carry space is the account's alone: anyone else holding a role there makes it a shared
727
+ // space, which members' own passes carry, each told of the line.
728
+ if (limits && (await sharedCarry(space, account))) {
729
+ if (!(await carriedByOther(space, id)))
730
+ await core.removeCarry(space);
731
+ throw new Error('That is a space others are members of, not a carry space');
732
+ }
177
733
  const before = subscription.carry;
178
734
  const attached = await write({ ...subscription, carry: { account, space, invite } });
179
735
  if (before && before.space !== space && !(await carriedByOther(before.space, id)))
@@ -213,11 +769,16 @@ export async function createHostNode(config) {
213
769
  const spaceId = spaceIdOf(id);
214
770
  return spaceId ? core.readKeyOf(spaceId) : null;
215
771
  },
216
- /** Drops what lapsed past its grace period. Run now and then. */
772
+ /** Drops what lapsed past its grace period, and free subscriptions idle too long. Run now and then. */
217
773
  async sweep() {
218
774
  const dropped = [];
219
- for (const subscription of await list()) {
220
- if (state(subscription) !== 'lapsed')
775
+ const idle = limits?.idleDays !== undefined ? limits.idleDays * DAY : null;
776
+ for (let subscription of await list()) {
777
+ // One from before idle subscriptions were dropped counts from now, not from when it was made.
778
+ if (idle !== null && plan(subscription) === 'free' && subscription.seen === undefined)
779
+ subscription = await write({ ...subscription, seen: now() });
780
+ const idled = idle !== null && plan(subscription) === 'free' && (subscription.seen ?? now()) + idle < now();
781
+ if (state(subscription) !== 'lapsed' && !idled)
221
782
  continue;
222
783
  await forget(subscription.id);
223
784
  const spaceId = spaceIdOf(subscription.id);
@@ -233,6 +794,11 @@ export async function createHostNode(config) {
233
794
  spaces: core.spaces,
234
795
  /** Reads every account's passes again, taking a space that waited for room: after what `full` says changed */
235
796
  recheck: () => core.refresh(),
797
+ /** Every space a subscription's carry space names, carried or not */
798
+ async namedFor(id) {
799
+ const space = (await read(id))?.carry?.space;
800
+ return [...(space ? (core.carries.get(space)?.named ?? []) : [])];
801
+ },
236
802
  /** How many spaces a subscription's account asks the host to carry */
237
803
  async carriedFor(id) {
238
804
  const space = (await read(id))?.carry?.space;