@estiva-app/conversation 0.39.0 → 0.41.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.
- package/CHANGELOG.md +67 -0
- package/README.md +7 -3
- package/dist/builders.d.ts +2 -1
- package/dist/builders.d.ts.map +1 -1
- package/dist/builders.js +2 -1
- package/dist/builders.js.map +1 -1
- package/dist/index.d.ts +5 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -4
- package/dist/index.js.map +1 -1
- package/dist/places.d.ts +61 -3
- package/dist/places.d.ts.map +1 -1
- package/dist/places.js +107 -9
- package/dist/places.js.map +1 -1
- package/dist/reactions.d.ts +80 -1
- package/dist/reactions.d.ts.map +1 -1
- package/dist/reactions.js +146 -1
- package/dist/reactions.js.map +1 -1
- package/dist/readState.d.ts +79 -12
- package/dist/readState.d.ts.map +1 -1
- package/dist/readState.js +192 -53
- package/dist/readState.js.map +1 -1
- package/dist/readStateQueue.d.ts +86 -0
- package/dist/readStateQueue.d.ts.map +1 -0
- package/dist/readStateQueue.js +292 -0
- package/dist/readStateQueue.js.map +1 -0
- package/package.json +3 -3
- package/src/builders.ts +2 -1
- package/src/index.ts +30 -1
- package/src/places.ts +167 -20
- package/src/reactions.ts +144 -2
- package/src/readState.ts +194 -49
- package/src/readStateQueue.ts +409 -0
package/src/reactions.ts
CHANGED
|
@@ -19,8 +19,8 @@
|
|
|
19
19
|
* - **Order** is presentation. This keeps first-reaction order; an app MAY
|
|
20
20
|
* sort by count, and two apps that differ there disagree about nothing.
|
|
21
21
|
*/
|
|
22
|
-
import type
|
|
23
|
-
import { isEventId, KIND_REACTION } from './kinds.js'
|
|
22
|
+
import { effectiveAuthor, type SignedEvent } from '@estiva-app/protocol'
|
|
23
|
+
import { isConversationKind, isEventId, KIND_DELETION, KIND_REACTION } from './kinds.js'
|
|
24
24
|
import { byOrder } from './order.js'
|
|
25
25
|
|
|
26
26
|
/**
|
|
@@ -149,3 +149,145 @@ export function groupReactions(reactions: readonly ReactionEvent[], viewer?: str
|
|
|
149
149
|
}
|
|
150
150
|
return out
|
|
151
151
|
}
|
|
152
|
+
|
|
153
|
+
// ── The reactions to a person — §6.6 *Finding the reactions to a person* ────
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* When the reactions to `P`'s messages start counting, unix seconds:
|
|
157
|
+
* 2026-11-13T17:00:00Z, just after every reaction began naming whose message
|
|
158
|
+
* it reacts to (ACT-6). One suite constant, set once: an earlier reaction
|
|
159
|
+
* carries no name, so it is never found, and every reader must agree on where
|
|
160
|
+
* orange starts.
|
|
161
|
+
*
|
|
162
|
+
* why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/a-reaction-names-whose-message-it-reacts-to.md
|
|
163
|
+
*/
|
|
164
|
+
export const REACTIONS_TO_ME_FROM = 1794589200
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* The read that answers "the reactions to `me`'s messages" (§6.6), stored and
|
|
168
|
+
* kept open: `{kinds:[7], "#p":[me], since}`, never earlier than
|
|
169
|
+
* {@link REACTIONS_TO_ME_FROM}.
|
|
170
|
+
*/
|
|
171
|
+
export function reactionsToMeFilter(me: string, since?: number): { kinds: number[]; '#p': string[]; since: number } {
|
|
172
|
+
return { kinds: [KIND_REACTION], '#p': [me], since: Math.max(since ?? REACTIONS_TO_ME_FROM, REACTIONS_TO_ME_FROM) }
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* The deletions that take a reaction to `me` back, or delete the message it
|
|
177
|
+
* reacted to later: `{kinds:[5], "#e":[…]}` over the reactions drawn **and**
|
|
178
|
+
* their targets, kept open. What it returns goes in {@link reactionsToMe}'s
|
|
179
|
+
* `deletions`. `null` when there is nothing to watch: skip the request, since
|
|
180
|
+
* an empty `#e` asks a relay for nothing or for everything.
|
|
181
|
+
*/
|
|
182
|
+
export function reactionTakeBackFilter(ids: readonly string[], since?: number): { kinds: number[]; '#e': string[]; since?: number } | null {
|
|
183
|
+
if (ids.length === 0) return null
|
|
184
|
+
return { kinds: [KIND_DELETION], '#e': [...new Set(ids)], ...(since !== undefined ? { since } : {}) }
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** How far ahead of the reader's clock a reaction may be dated and still count, in seconds. */
|
|
188
|
+
const CLOCK_SKEW_S = 60
|
|
189
|
+
|
|
190
|
+
/** One reaction to `me`'s message, kept by §6.6. */
|
|
191
|
+
export interface ReactionToMe {
|
|
192
|
+
/** The reaction's event id. */
|
|
193
|
+
id: string
|
|
194
|
+
/** Who reacted: the reaction's effective author. */
|
|
195
|
+
by: string
|
|
196
|
+
/** Its `created_at`, unix seconds. */
|
|
197
|
+
at: number
|
|
198
|
+
/** {@link reactionEmojiOf}. */
|
|
199
|
+
emoji: string
|
|
200
|
+
/** The id of the message it reacts to. */
|
|
201
|
+
target: string
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
type Tagged = Pick<SignedEvent, 'pubkey' | 'kind' | 'tags' | 'created_at'>
|
|
205
|
+
|
|
206
|
+
const lastP = (event: Pick<SignedEvent, 'tags'>): string | undefined => {
|
|
207
|
+
for (let i = event.tags.length - 1; i >= 0; i--) if (event.tags[i][0] === 'p') return event.tags[i][1]
|
|
208
|
+
return undefined
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* Whether a reader keeps a reaction as one to `me`'s message (§6.6, exactly):
|
|
213
|
+
*
|
|
214
|
+
* - its **last** `p` is `me`;
|
|
215
|
+
* - its target (the last 64-hex `e`) is held, is a message or a comment
|
|
216
|
+
* (`kind:9` or `1111`), and `me` is its effective author, worked out with the
|
|
217
|
+
* relay's key — so a reaction that names `me` falsely, or beside someone
|
|
218
|
+
* else, keeps nothing, and without the key a message the relay signed on
|
|
219
|
+
* `me`'s behalf is the relay's;
|
|
220
|
+
* - `me` is not the reaction's effective author;
|
|
221
|
+
* - it is from {@link REACTIONS_TO_ME_FROM} on, and not more than 60 s ahead of
|
|
222
|
+
* `nowMs`: one dated in the future would stay orange past every "seen"
|
|
223
|
+
* written at the time it was shown.
|
|
224
|
+
*
|
|
225
|
+
* `target` is the event the reader fetched by id; undefined when it is deleted
|
|
226
|
+
* or unreadable, which keeps nothing.
|
|
227
|
+
*/
|
|
228
|
+
export function keepReactionToMe(
|
|
229
|
+
reaction: Tagged & Pick<SignedEvent, 'id'>,
|
|
230
|
+
target: (Tagged & Pick<SignedEvent, 'id'>) | undefined,
|
|
231
|
+
me: string,
|
|
232
|
+
relayKey?: string | null,
|
|
233
|
+
nowMs: number = Date.now(),
|
|
234
|
+
): boolean {
|
|
235
|
+
if (reaction.kind !== KIND_REACTION || reaction.created_at < REACTIONS_TO_ME_FROM) return false
|
|
236
|
+
if (reaction.created_at > Math.floor(nowMs / 1000) + CLOCK_SKEW_S) return false
|
|
237
|
+
if (lastP(reaction) !== me) return false
|
|
238
|
+
if (!target || reactionTargetOf(reaction) !== target.id.toLowerCase()) return false
|
|
239
|
+
if (!isConversationKind(target.kind)) return false
|
|
240
|
+
if (effectiveAuthor(target, relayKey) !== me) return false
|
|
241
|
+
return effectiveAuthor(reaction, relayKey) !== me
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* The reactions to `me`'s messages, kept by {@link keepReactionToMe}, newest
|
|
246
|
+
* first, one per `(by, target, emoji)` (the earliest, as §6.6 counts).
|
|
247
|
+
* `deletions` are the `kind:5` events read with {@link reactionTakeBackFilter}:
|
|
248
|
+
* one signed by a reaction's author takes that reaction back, and one signed by
|
|
249
|
+
* a target's effective author deletes that message, so none of its reactions
|
|
250
|
+
* lights. A `kind:5` by anybody else removes nothing. `targetsById` holds the
|
|
251
|
+
* targets the reader has, by lowercase id.
|
|
252
|
+
*/
|
|
253
|
+
export function reactionsToMe(
|
|
254
|
+
reactions: readonly SignedEvent[],
|
|
255
|
+
targetsById: ReadonlyMap<string, Tagged & Pick<SignedEvent, 'id'>>,
|
|
256
|
+
me: string,
|
|
257
|
+
opts: { relayKey?: string | null; deletions?: readonly SignedEvent[]; nowMs?: number } = {},
|
|
258
|
+
): ReactionToMe[] {
|
|
259
|
+
const { relayKey, nowMs = Date.now() } = opts
|
|
260
|
+
// Event id → who deleted it, by effective author, so each removal is checked against the author of what it names.
|
|
261
|
+
const deletedBy = new Map<string, Set<string>>()
|
|
262
|
+
for (const deletion of opts.deletions ?? []) {
|
|
263
|
+
if (deletion.kind !== KIND_DELETION) continue
|
|
264
|
+
const signer = effectiveAuthor(deletion, relayKey)
|
|
265
|
+
for (const t of deletion.tags) {
|
|
266
|
+
if (t[0] !== 'e' || !isEventId(t[1])) continue
|
|
267
|
+
const id = t[1].toLowerCase()
|
|
268
|
+
const by = deletedBy.get(id) ?? new Set<string>()
|
|
269
|
+
by.add(signer)
|
|
270
|
+
deletedBy.set(id, by)
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
const deleted = (event: Tagged & Pick<SignedEvent, 'id'>) => deletedBy.get(event.id.toLowerCase())?.has(effectiveAuthor(event, relayKey)) ?? false
|
|
274
|
+
const out: ReactionToMe[] = []
|
|
275
|
+
const counted = new Set<string>()
|
|
276
|
+
const seen = new Set<string>()
|
|
277
|
+
for (const reaction of [...reactions].sort(byOrder)) {
|
|
278
|
+
if (seen.has(reaction.id)) continue
|
|
279
|
+
seen.add(reaction.id)
|
|
280
|
+
if (deleted(reaction)) continue
|
|
281
|
+
const target = reactionTargetOf(reaction)
|
|
282
|
+
const held = target === undefined ? undefined : targetsById.get(target)
|
|
283
|
+
if (target === undefined || (held !== undefined && deleted(held))) continue
|
|
284
|
+
if (!keepReactionToMe(reaction, held, me, relayKey, nowMs)) continue
|
|
285
|
+
const by = effectiveAuthor(reaction, relayKey)
|
|
286
|
+
const emoji = reactionEmojiOf(reaction)
|
|
287
|
+
const key = JSON.stringify([by, target, emoji])
|
|
288
|
+
if (counted.has(key)) continue
|
|
289
|
+
counted.add(key)
|
|
290
|
+
out.push({ id: reaction.id, by, at: reaction.created_at, emoji, target })
|
|
291
|
+
}
|
|
292
|
+
return out.reverse()
|
|
293
|
+
}
|
package/src/readState.ts
CHANGED
|
@@ -78,6 +78,37 @@ export const THREAD_RULE_FROM = 1791226800
|
|
|
78
78
|
*/
|
|
79
79
|
export const REPLY_FLOOR_CONTEXT = 'reply-floor'
|
|
80
80
|
|
|
81
|
+
/**
|
|
82
|
+
* The reserved context of the reactions floor (§11.1, §11.6, ACT-7): every
|
|
83
|
+
* reaction to `P`'s message at or before it counts as seen. Raised, never
|
|
84
|
+
* lowered, when a cap drops a `reactions:` key — to that key's value — as
|
|
85
|
+
* {@link REPLY_FLOOR_CONTEXT} is for a `thread:` key, so a reaction somebody
|
|
86
|
+
* saw never turns a place orange again.
|
|
87
|
+
*
|
|
88
|
+
* why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/a-reaction-is-seen-once-in-its-conversation.md
|
|
89
|
+
* why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/reactions-seen-is-kept-under-reactions-and-opening-it-sees-it.md
|
|
90
|
+
*/
|
|
91
|
+
export const REACTIONS_FLOOR_CONTEXT = 'reactions-floor'
|
|
92
|
+
|
|
93
|
+
const REACTIONS_PREFIX = 'reactions:'
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Where "seen" is kept for the reactions to `P`'s messages in one conversation
|
|
97
|
+
* (§11.1, ACT-7): `reactions:` + the stream's context — `reactions:file:<d>`,
|
|
98
|
+
* `reactions:<file address>`, `reactions:<channel uuid>`. A reaction on a reply
|
|
99
|
+
* counts in its root's stream. It has no parent (§11.3): no stream, thread or
|
|
100
|
+
* floor marker reaches it, and it reaches none of them, so opening a file
|
|
101
|
+
* clears none of its reactions and seeing them reads none of its messages.
|
|
102
|
+
*
|
|
103
|
+
* why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/a-reaction-is-seen-once-in-its-conversation.md
|
|
104
|
+
* why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/reactions-seen-is-kept-under-reactions-and-opening-it-sees-it.md
|
|
105
|
+
*/
|
|
106
|
+
export function reactionsContext(context: string): string {
|
|
107
|
+
return `${REACTIONS_PREFIX}${context}`
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const isReactionsKey = (key: string) => key.startsWith(REACTIONS_PREFIX)
|
|
111
|
+
|
|
81
112
|
const EVENT_ID_RE = /^[0-9a-f]{64}$/
|
|
82
113
|
const SLOT_ID_RE = /^[0-9a-f]{32}$/
|
|
83
114
|
|
|
@@ -156,6 +187,30 @@ export function streamMarkerOf(merged: Readonly<Record<string, number>>, stream:
|
|
|
156
187
|
return out
|
|
157
188
|
}
|
|
158
189
|
|
|
190
|
+
/**
|
|
191
|
+
* Until when the reactions to `P`'s messages in one conversation are seen
|
|
192
|
+
* (§11.3, §11.6, ACT-7): the later of `reactions:<context>` over the stream's
|
|
193
|
+
* contexts and the reactions floor. A file is named both ways — pass its
|
|
194
|
+
* address and `file:<d>`; an address whose `d` is a file id reads
|
|
195
|
+
* `reactions:file:<d>` as well. Nothing else reaches it: no stream, thread or
|
|
196
|
+
* reply-floor marker. Unix seconds; 0 when nothing is held, which is earlier
|
|
197
|
+
* than every reaction that counts.
|
|
198
|
+
*
|
|
199
|
+
* why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/a-reaction-is-seen-once-in-its-conversation.md
|
|
200
|
+
*/
|
|
201
|
+
export function reactionsSeenOf(merged: Readonly<Record<string, number>>, streamContexts: readonly string[]): number {
|
|
202
|
+
let out = merged[REACTIONS_FLOOR_CONTEXT] ?? 0
|
|
203
|
+
const read = (context: string | undefined) => {
|
|
204
|
+
const at = context === undefined ? undefined : merged[reactionsContext(context)]
|
|
205
|
+
if (at !== undefined && at > out) out = at
|
|
206
|
+
}
|
|
207
|
+
for (const context of streamContexts) {
|
|
208
|
+
read(context)
|
|
209
|
+
if (ADDRESS_RE.test(context)) read(fileIdContext(fileIdOf(context)))
|
|
210
|
+
}
|
|
211
|
+
return out
|
|
212
|
+
}
|
|
213
|
+
|
|
159
214
|
/** `thread:<root-event-id>`, NIP-RS's own scheme. */
|
|
160
215
|
export function threadContext(rootEventId: string | null | undefined): string | undefined {
|
|
161
216
|
if (!rootEventId) return undefined
|
|
@@ -178,13 +233,22 @@ export function toContextSeconds(atMs: number): number {
|
|
|
178
233
|
}
|
|
179
234
|
|
|
180
235
|
/**
|
|
181
|
-
* Is this a context id
|
|
182
|
-
*
|
|
183
|
-
* The reserved `folder:` is
|
|
236
|
+
* Is this a context id this code **writes and judges**: a channel uuid, a file
|
|
237
|
+
* address, `file:<d>`, `thread:`/`msg:` with 64 lowercase hex, `reactions:`
|
|
238
|
+
* before any of those, or one of the two floors. The reserved `folder:` is
|
|
239
|
+
* refused until §11.5 specifies it.
|
|
240
|
+
*
|
|
241
|
+
* Only what an app writes must pass it ({@link advanceContexts}' updates).
|
|
242
|
+
* What a blob already holds is carried by {@link isCarriedContextId}.
|
|
184
243
|
*/
|
|
185
244
|
export function isPublishableContextId(id: string): boolean {
|
|
186
|
-
if (id === REPLY_FLOOR_CONTEXT) return true
|
|
245
|
+
if (id === REPLY_FLOOR_CONTEXT || id === REACTIONS_FLOOR_CONTEXT) return true
|
|
187
246
|
if (id.length === 0 || utf8(id) > MAX_CONTEXT_ID_BYTES) return false
|
|
247
|
+
return isReactionsKey(id) ? isConversationContextId(id.slice(REACTIONS_PREFIX.length)) : isConversationContextId(id)
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** A context of one conversation's own marker (§11.1): not a floor, not a `reactions:` key. */
|
|
251
|
+
function isConversationContextId(id: string): boolean {
|
|
188
252
|
if (id.startsWith('thread:')) return EVENT_ID_RE.test(id.slice('thread:'.length))
|
|
189
253
|
if (id.startsWith('msg:')) return EVENT_ID_RE.test(id.slice('msg:'.length))
|
|
190
254
|
// A key beginning `file:` whose remainder is not a lowercase UUID is not a file context (§11.1).
|
|
@@ -192,6 +256,39 @@ export function isPublishableContextId(id: string): boolean {
|
|
|
192
256
|
return UUID_RE.test(id) || ADDRESS_RE.test(id)
|
|
193
257
|
}
|
|
194
258
|
|
|
259
|
+
/**
|
|
260
|
+
* Is this a key a blob **carries**, known or not (§11.1, ACT-7): any non-empty
|
|
261
|
+
* string of at most {@link MAX_CONTEXT_ID_BYTES} bytes. A key this code does not
|
|
262
|
+
* know — another app's, a later version's — is kept verbatim through
|
|
263
|
+
* {@link parseReadStateBlob}, {@link mergeSlots}, {@link advanceContexts} and
|
|
264
|
+
* {@link publishReadState}, and never judged: dropping it would erase what a
|
|
265
|
+
* newer app wrote every time an older one republished its slot. Judging is
|
|
266
|
+
* {@link isPublishableContextId}'s.
|
|
267
|
+
*/
|
|
268
|
+
export function isCarriedContextId(id: string): boolean {
|
|
269
|
+
return typeof id === 'string' && id.length > 0 && id !== '__proto__' && utf8(id) <= MAX_CONTEXT_ID_BYTES
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/** A blob's carried entries: every {@link isCarriedContextId} key with a valid timestamp. */
|
|
273
|
+
function carried(contexts: Readonly<Record<string, unknown>>): Record<string, number> {
|
|
274
|
+
const out = contextMap()
|
|
275
|
+
for (const [key, value] of Object.entries(contexts)) if (isCarriedContextId(key) && isTimestamp(value)) out[key] = value
|
|
276
|
+
return out
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/**
|
|
280
|
+
* An empty context map. A carried key may be named like a member of `Object.prototype` (`constructor`, `toString`,
|
|
281
|
+
* `valueOf`): it is an own property here, so every lookup of a key read from a blob checks {@link has}, never
|
|
282
|
+
* `map[key] === undefined`. A non-enumerable `Symbol.toPrimitive` keeps the map printable (`String(map)`) when an own
|
|
283
|
+
* `toString` or `valueOf` key shadows the prototype's; it is not a key, so nothing serialises or compares it.
|
|
284
|
+
*/
|
|
285
|
+
function contextMap(): Record<string, number> {
|
|
286
|
+
return Object.defineProperty({}, Symbol.toPrimitive, { value: () => '[object Object]', enumerable: false })
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/** Whether the map holds `key` itself, not by its prototype. */
|
|
290
|
+
const has = (map: Readonly<Record<string, number>>, key: string): boolean => Object.prototype.hasOwnProperty.call(map, key)
|
|
291
|
+
|
|
195
292
|
const isTimestamp = (value: unknown): value is number =>
|
|
196
293
|
typeof value === 'number' && Number.isInteger(value) && value >= 0 && value <= MAX_TIMESTAMP
|
|
197
294
|
|
|
@@ -315,17 +412,14 @@ export function parseReadStateBlob(plaintext: string | undefined): ReadStateBlob
|
|
|
315
412
|
if (blob.v !== 1) return undefined
|
|
316
413
|
const clientId =
|
|
317
414
|
typeof blob.client_id === 'string' && blob.client_id.length >= 1 && utf8(blob.client_id) <= MAX_CLIENT_ID_BYTES ? blob.client_id : ''
|
|
318
|
-
const contexts: Record<string, number> = {}
|
|
319
415
|
const source = typeof blob.contexts === 'object' && blob.contexts !== null ? blob.contexts : {}
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
}
|
|
323
|
-
return { v: 1, client_id: clientId, contexts }
|
|
416
|
+
// Every well-formed key is kept, known or not (§11.1): an unknown one is carried, never judged.
|
|
417
|
+
return { v: 1, client_id: clientId, contexts: carried(source as Record<string, unknown>) }
|
|
324
418
|
}
|
|
325
419
|
|
|
326
420
|
/** Serialize for encryption, keys sorted, so an unchanged set is an unchanged string. */
|
|
327
421
|
export function serializeReadStateBlob(blob: ReadStateBlob): string {
|
|
328
|
-
const contexts
|
|
422
|
+
const contexts = contextMap()
|
|
329
423
|
for (const key of Object.keys(blob.contexts).sort()) contexts[key] = blob.contexts[key]
|
|
330
424
|
return JSON.stringify({ v: blob.v, client_id: blob.client_id, contexts })
|
|
331
425
|
}
|
|
@@ -351,7 +445,7 @@ const byNewestThenKey = (contexts: Readonly<Record<string, number>>) => (a: stri
|
|
|
351
445
|
export function capContextsToBytes(contexts: Readonly<Record<string, number>>, budget: number = MAX_CONTEXTS_BYTES): CappedContexts {
|
|
352
446
|
const cost = (key: string, value: number) => utf8(JSON.stringify(key)) + 1 + String(value).length
|
|
353
447
|
const keys = Object.keys(contexts).sort(byNewestThenKey(contexts))
|
|
354
|
-
const kept
|
|
448
|
+
const kept = contextMap()
|
|
355
449
|
let bytes = 2
|
|
356
450
|
for (let i = 0; i < keys.length; i++) {
|
|
357
451
|
const key = keys[i]
|
|
@@ -363,40 +457,73 @@ export function capContextsToBytes(contexts: Readonly<Record<string, number>>, b
|
|
|
363
457
|
return { contexts: kept, bytes, evicted: [] }
|
|
364
458
|
}
|
|
365
459
|
|
|
366
|
-
const isThreadKey = (key: string) => key.startsWith('thread:')
|
|
460
|
+
const isThreadKey = (key: string) => key.startsWith('thread:') && isPublishableContextId(key)
|
|
367
461
|
|
|
368
462
|
/**
|
|
369
|
-
*
|
|
370
|
-
*
|
|
371
|
-
*
|
|
372
|
-
*
|
|
373
|
-
|
|
463
|
+
* The two floors (§11.6), and the keys each pays for when a cap drops them: the
|
|
464
|
+
* reply floor for a `thread:` marker, the reactions floor for a `reactions:`
|
|
465
|
+
* key. A key nobody knows pays for nothing: it is never judged, so dropping it
|
|
466
|
+
* costs nothing that a floor would have to hold.
|
|
467
|
+
*/
|
|
468
|
+
export const FLOORS: readonly { context: string; pays: (key: string) => boolean }[] = [
|
|
469
|
+
{ context: REPLY_FLOOR_CONTEXT, pays: isThreadKey },
|
|
470
|
+
{ context: REACTIONS_FLOOR_CONTEXT, pays: (key) => isReactionsKey(key) && isPublishableContextId(key) },
|
|
471
|
+
]
|
|
472
|
+
|
|
473
|
+
const isFloor = (key: string) => key === REPLY_FLOOR_CONTEXT || key === REACTIONS_FLOOR_CONTEXT
|
|
474
|
+
|
|
475
|
+
/** A context map split into its floors and everything else. */
|
|
476
|
+
export function splitFloors(contexts: Readonly<Record<string, number>>): { floors: Record<string, number>; markers: Record<string, number> } {
|
|
477
|
+
const floors = contextMap()
|
|
478
|
+
const markers = contextMap()
|
|
479
|
+
for (const [key, value] of Object.entries(contexts)) (isFloor(key) ? floors : markers)[key] = value
|
|
480
|
+
return { floors, markers }
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
/**
|
|
484
|
+
* {@link capContextsToBytes} for a read-state blob (§11.6): a floor is never
|
|
485
|
+
* evicted, and dropping a `thread:` marker first raises the reply floor to its
|
|
486
|
+
* value, dropping a `reactions:` key the reactions floor. Under the thread rule
|
|
487
|
+
* a `thread:` marker is never made redundant by its stream, and a `reactions:`
|
|
488
|
+
* key has no parent at all, so without the floors every eviction would light
|
|
489
|
+
* what the person already read or saw. Deterministic and idempotent, like the
|
|
490
|
+
* cap it wraps.
|
|
374
491
|
*/
|
|
375
492
|
export function capReadStateContexts(contexts: Readonly<Record<string, number>>, budget: number = MAX_CONTEXTS_BYTES): CappedContexts {
|
|
376
|
-
const {
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
493
|
+
const { floors: held, markers: rest } = splitFloors(contexts)
|
|
494
|
+
// A floor's slot is set aside first, at the widest value it can hold, so raising it never overflows. Only the floors
|
|
495
|
+
// held or needed are reserved, so a blob with no thread or reactions key evicted is capped as before.
|
|
496
|
+
const needed = new Set(Object.keys(held))
|
|
497
|
+
for (;;) {
|
|
498
|
+
const reserve = [...needed].reduce((sum, floor) => sum + utf8(JSON.stringify(floor)) + 1 + String(MAX_TIMESTAMP).length + 1, 0)
|
|
499
|
+
const capped = capContextsToBytes(rest, budget - reserve)
|
|
500
|
+
const more = FLOORS.filter((f) => !needed.has(f.context) && capped.evicted.some(f.pays))
|
|
501
|
+
if (more.length > 0) {
|
|
502
|
+
for (const f of more) needed.add(f.context)
|
|
503
|
+
continue
|
|
504
|
+
}
|
|
505
|
+
if (needed.size === 0) return capped
|
|
506
|
+
const kept = Object.assign(contextMap(), capped.contexts)
|
|
507
|
+
for (const f of FLOORS) {
|
|
508
|
+
if (!needed.has(f.context)) continue
|
|
509
|
+
kept[f.context] = capped.evicted.reduce((max, key) => (f.pays(key) && rest[key] > max ? rest[key] : max), held[f.context] ?? 0)
|
|
510
|
+
}
|
|
511
|
+
return { contexts: kept, bytes: utf8(JSON.stringify(kept)), evicted: capped.evicted }
|
|
380
512
|
}
|
|
381
|
-
// The floor's slot is set aside first, at the widest value it can hold, so raising it never overflows.
|
|
382
|
-
const reserve = utf8(JSON.stringify(REPLY_FLOOR_CONTEXT)) + 1 + String(MAX_TIMESTAMP).length + 1
|
|
383
|
-
const capped = capContextsToBytes(rest, budget - reserve)
|
|
384
|
-
const raised = capped.evicted.reduce((max, key) => (isThreadKey(key) && rest[key] > max ? rest[key] : max), floor ?? 0)
|
|
385
|
-
const kept = { ...capped.contexts, [REPLY_FLOOR_CONTEXT]: raised }
|
|
386
|
-
return { contexts: kept, bytes: utf8(JSON.stringify(kept)), evicted: capped.evicted }
|
|
387
513
|
}
|
|
388
514
|
|
|
389
515
|
/**
|
|
390
516
|
* Apply markers, taking the later of each (§11.4: never lower one), then cap.
|
|
391
|
-
* Unpublishable ids and out-of-range timestamps are dropped,
|
|
392
|
-
*
|
|
393
|
-
*
|
|
517
|
+
* Unpublishable ids and out-of-range timestamps among the updates are dropped,
|
|
518
|
+
* and so is a floor: only the cap raises one (§11.6), so a stray value cannot
|
|
519
|
+
* mark every reply read or every reaction seen. What `current` holds is
|
|
520
|
+
* carried, a key this code does not know and the floors included (§11.1).
|
|
394
521
|
*/
|
|
395
522
|
export function advanceContexts(current: Readonly<Record<string, number>>, updates: Readonly<Record<string, number>>): CappedContexts {
|
|
396
|
-
const next: Record<string, number> =
|
|
523
|
+
const next: Record<string, number> = carried(current)
|
|
397
524
|
for (const [id, seconds] of Object.entries(updates)) {
|
|
398
|
-
if (id
|
|
399
|
-
if (next
|
|
525
|
+
if (isFloor(id) || !isPublishableContextId(id) || !isTimestamp(seconds)) continue
|
|
526
|
+
if (!has(next, id) || seconds > next[id]) next[id] = seconds
|
|
400
527
|
}
|
|
401
528
|
return capReadStateContexts(next)
|
|
402
529
|
}
|
|
@@ -442,24 +569,35 @@ export interface SlotBlob {
|
|
|
442
569
|
|
|
443
570
|
/** Every slot merged by the max rule, capped at {@link MAX_CONTEXTS} newest first, ties by key. */
|
|
444
571
|
export function mergeSlots(slots: readonly (Pick<SlotBlob, 'blob'> & { createdAt?: number })[]): Record<string, number> {
|
|
445
|
-
const merged
|
|
572
|
+
const merged = contextMap()
|
|
446
573
|
for (const { blob, createdAt } of slots) {
|
|
447
|
-
|
|
448
|
-
|
|
574
|
+
// Every well-formed key, known or not, is carried (§11.1); only the known ones are ever judged.
|
|
575
|
+
for (const [id, value] of Object.entries(carried(blob.contexts))) {
|
|
449
576
|
// A floor is the value of a marker the cap dropped, so never later than the blob that holds it (§11.6).
|
|
450
|
-
const seconds = id
|
|
451
|
-
if (merged
|
|
577
|
+
const seconds = isFloor(id) && createdAt !== undefined ? Math.min(value, createdAt) : value
|
|
578
|
+
if (!has(merged, id) || seconds > merged[id]) merged[id] = seconds
|
|
452
579
|
}
|
|
453
580
|
}
|
|
454
|
-
const {
|
|
581
|
+
const { floors, markers: rest } = splitFloors(merged)
|
|
455
582
|
const keys = Object.keys(rest)
|
|
456
|
-
if (keys.length + (
|
|
457
|
-
// Over the count cap, as over the byte cap: the
|
|
583
|
+
if (keys.length + Object.keys(floors).length <= MAX_CONTEXTS) return merged
|
|
584
|
+
// Over the count cap, as over the byte cap: the floors stay, each paying for the keys it covers that are dropped.
|
|
458
585
|
const sorted = keys.sort(byNewestThenKey(rest))
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
586
|
+
// Room is kept for each floor held or needed, so the merged view is at most MAX_CONTEXTS keys, floors included.
|
|
587
|
+
const needed = new Set(Object.keys(floors))
|
|
588
|
+
let room = MAX_CONTEXTS - needed.size
|
|
589
|
+
for (const f of FLOORS) {
|
|
590
|
+
if (needed.has(f.context) || !sorted.slice(room - 1).some(f.pays)) continue
|
|
591
|
+
needed.add(f.context)
|
|
592
|
+
room -= 1
|
|
593
|
+
}
|
|
594
|
+
const kept = contextMap()
|
|
595
|
+
for (const id of sorted.slice(0, room)) kept[id] = rest[id]
|
|
596
|
+
const dropped = sorted.slice(room)
|
|
597
|
+
for (const f of FLOORS) {
|
|
598
|
+
if (!needed.has(f.context)) continue
|
|
599
|
+
kept[f.context] = dropped.reduce((max, key) => (f.pays(key) && rest[key] > max ? rest[key] : max), floors[f.context] ?? 0)
|
|
600
|
+
}
|
|
463
601
|
return kept
|
|
464
602
|
}
|
|
465
603
|
|
|
@@ -503,6 +641,8 @@ export function effectiveReadAt(
|
|
|
503
641
|
from: number = THREAD_RULE_FROM,
|
|
504
642
|
): number | undefined {
|
|
505
643
|
const own = merged[context]
|
|
644
|
+
// A `reactions:` key has no parent (§11.3): no stream's marker reaches it, only the reactions floor.
|
|
645
|
+
if (isReactionsKey(context)) return later(own, merged[REACTIONS_FLOOR_CONTEXT])
|
|
506
646
|
const parent = stream === undefined ? undefined : streamMarkerOf(merged, stream)
|
|
507
647
|
if (isThreadKey(context)) return threadReadAt({ thread: own, stream: parent, floor: merged[REPLY_FLOOR_CONTEXT] }, from)
|
|
508
648
|
return later(own, parent)
|
|
@@ -733,11 +873,16 @@ export async function publishReadState(
|
|
|
733
873
|
identity: SlotIdentity,
|
|
734
874
|
contexts: Readonly<Record<string, number>>,
|
|
735
875
|
nowMs: number,
|
|
876
|
+
slot?: Readonly<Record<string, number>>,
|
|
736
877
|
): Promise<{ ok: boolean; reason?: string }> {
|
|
737
|
-
// Filtered here as well: the blob is grow-only, and a map built outside `advanceContexts` must not put an id into
|
|
738
|
-
//
|
|
739
|
-
|
|
740
|
-
|
|
878
|
+
// Filtered here as well: the blob is grow-only, and a map built outside `advanceContexts` must not put an id into
|
|
879
|
+
// it, so the caller's markers go in as updates, through the gate. The floors go in as `current`, since
|
|
880
|
+
// `advanceContexts` refuses one among the updates. What `slot` — this slot as read back — already holds is carried
|
|
881
|
+
// verbatim, a key this code does not know included: another app or a later version wrote it, and republishing the
|
|
882
|
+
// slot must not erase it (§11.1). A key that is in neither is never written.
|
|
883
|
+
const { floors, markers } = splitFloors(contexts)
|
|
884
|
+
const held = carried(slot ?? {})
|
|
885
|
+
for (const [floor, at] of Object.entries(carried(floors))) held[floor] = has(held, floor) ? Math.max(at, held[floor]) : at
|
|
741
886
|
const plaintext = serializeReadStateBlob({ v: 1, client_id: identity.clientId, contexts: advanceContexts(held, markers).contexts })
|
|
742
887
|
if (utf8(plaintext) > MAX_BLOB_BYTES) return { ok: false, reason: `read state is ${utf8(plaintext)} bytes, over ${MAX_BLOB_BYTES}` }
|
|
743
888
|
const ciphertext = await deps.nip44.encrypt(plaintext)
|