@peerbit/program 1.0.6 → 2.0.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/src/index.ts CHANGED
@@ -1,526 +1,7 @@
1
- import { PublicSignKey, getPublicKeyFromPeerId } from "@peerbit/crypto";
2
- import { Constructor, getSchema, option, variant } from "@dao-xyz/borsh";
3
- import { getValuesWithType } from "./utils.js";
4
- import { serialize, deserialize } from "@dao-xyz/borsh";
5
- import { CustomEvent, EventEmitter } from "@libp2p/interfaces/events";
6
- import { Client } from "./node.js";
7
- import { waitForAsync } from "@peerbit/time";
8
- import { Blocks } from "@peerbit/blocks-interface";
9
- import { PeerId as Libp2pPeerId } from "@libp2p/interface-peer-id";
10
- import {
11
- SubscriptionEvent,
12
- UnsubcriptionEvent,
13
- } from "@peerbit/pubsub-interface";
14
- import { Address } from "./address.js";
15
-
16
- export type { Address };
17
-
18
- export interface Addressable {
19
- address?: Address | undefined;
20
- }
21
-
22
- const intersection = (
23
- a: Set<string> | undefined,
24
- b: Set<string> | IterableIterator<string>
25
- ) => {
26
- const newSet = new Set<string>();
27
- for (const el of b) {
28
- if (!a || a.has(el)) {
29
- newSet.add(el);
30
- }
31
- }
32
- return newSet;
33
- };
34
-
35
- export interface Saveable {
36
- save(
37
- store: Blocks,
38
- options?: {
39
- format?: string;
40
- timeout?: number;
41
- }
42
- ): Promise<Address>;
43
-
44
- delete(): Promise<void>;
45
- }
46
-
47
- export type OpenProgram = (program: Program) => Promise<Program>;
48
-
49
- export interface NetworkEvents {
50
- join: CustomEvent<PublicSignKey>;
51
- leave: CustomEvent<PublicSignKey>;
52
- }
53
-
54
- export interface LifeCycleEvents {
55
- drop: CustomEvent<Program>;
56
- open: CustomEvent<Program>;
57
- close: CustomEvent<Program>;
58
- }
59
-
60
- export interface ProgramEvents extends NetworkEvents, LifeCycleEvents {}
61
-
62
- type EventOptions = {
63
- onBeforeOpen?: (program: AbstractProgram<any>) => Promise<void> | void;
64
- onOpen?: (program: AbstractProgram<any>) => Promise<void> | void;
65
- onDrop?: (program: AbstractProgram<any>) => Promise<void> | void;
66
- onClose?: (program: AbstractProgram<any>) => Promise<void> | void;
67
- };
68
-
69
- export type ProgramInitializationOptions<Args> = {
70
- // TODO
71
- // reset: boolean
72
- args?: Args;
73
- parent?: AbstractProgram;
74
- } & EventOptions;
75
-
76
- const getAllParentAddresses = (p: AbstractProgram): string[] => {
77
- return getAllParent(p, [])
78
- .filter((x) => x instanceof Program)
79
- .map((x) => (x as Program).address);
80
- };
81
-
82
- const getAllParent = (
83
- a: AbstractProgram,
84
- arr: AbstractProgram[] = [],
85
- includeThis = false
86
- ) => {
87
- includeThis && arr.push(a);
88
- if (a.parents) {
89
- for (const p of a.parents) {
90
- if (p) {
91
- getAllParent(p, arr, true);
92
- }
93
- }
94
- }
95
- return arr;
96
- };
97
-
98
- export type ProgramClient = Client<Program, AbstractProgram>;
99
-
100
- @variant(0)
101
- export abstract class AbstractProgram<
102
- Args = any,
103
- Events extends ProgramEvents = ProgramEvents
104
- > {
105
- private _node: ProgramClient;
106
- private _allPrograms: AbstractProgram[] | undefined;
107
-
108
- private _events: EventEmitter<ProgramEvents>;
109
- private _closed: boolean;
110
-
111
- parents: (AbstractProgram | undefined)[];
112
- children: AbstractProgram[];
113
-
114
- addParent(program: AbstractProgram | undefined) {
115
- (this.parents || (this.parents = [])).push(program);
116
- if (program) {
117
- (program.children || (program.children = [])).push(this);
118
- }
119
- }
120
-
121
- get events(): EventEmitter<Events> {
122
- return this._events || (this._events = new EventEmitter());
123
- }
124
-
125
- get closed(): boolean {
126
- if (this._closed == null) {
127
- return true;
128
- }
129
- return this._closed;
130
- }
131
- set closed(closed: boolean) {
132
- this._closed = closed;
133
- }
134
-
135
- get node(): ProgramClient {
136
- return this._node;
137
- }
138
-
139
- set node(node: ProgramClient) {
140
- this._node = node;
141
- }
142
-
143
- private _eventOptions: EventOptions | undefined;
144
-
145
- async beforeOpen(
146
- node: ProgramClient,
147
- options?: ProgramInitializationOptions<Args>
148
- ) {
149
- if (!this.closed) {
150
- this.addParent(options?.parent);
151
- return this;
152
- } else {
153
- this.addParent(options?.parent);
154
- }
155
- this._eventOptions = options;
156
- this.node = node;
157
- const nexts = this.programs;
158
- for (const next of nexts) {
159
- await next.beforeOpen(node, { ...options, parent: this });
160
- }
161
-
162
- this.node.services.pubsub.addEventListener(
163
- "subscribe",
164
- this._subscriptionEventListener ||
165
- (this._subscriptionEventListener = (s) =>
166
- !this.closed && this._emitJoinNetworkEvents(s.detail))
167
- );
168
- this.node.services.pubsub.addEventListener(
169
- "unsubscribe",
170
- this._unsubscriptionEventListener ||
171
- (this._unsubscriptionEventListener = (s) =>
172
- !this.closed && this._emitLeaveNetworkEvents(s.detail))
173
- );
174
-
175
- await this._eventOptions?.onBeforeOpen?.(this);
176
- return this;
177
- }
178
-
179
- async afterOpen() {
180
- this.emitEvent(new CustomEvent("open", { detail: this }), true);
181
- await this._eventOptions?.onOpen?.(this);
182
- this.closed = false;
183
- const nexts = this.programs;
184
- for (const next of nexts) {
185
- await next.afterOpen();
186
- }
187
- return this;
188
- }
189
-
190
- abstract open(args?: Args): Promise<void>;
191
-
192
- private _clear() {
193
- this._allPrograms = undefined;
194
- }
195
-
196
- private async _emitJoinNetworkEvents(s: SubscriptionEvent) {
197
- const allTopics = this.programs
198
- .map((x) => x.getTopics?.())
199
- .filter((x) => x)
200
- .flat() as string[];
201
-
202
- // if subscribing to all topics, emit "join" event
203
- for (const topic of allTopics) {
204
- if (
205
- !this.node.services.pubsub.getSubscribers(topic)?.has(s.from.hashcode())
206
- ) {
207
- return;
208
- }
209
- }
210
- this.events.dispatchEvent(new CustomEvent("join", { detail: s.from }));
211
- }
212
-
213
- private async _emitLeaveNetworkEvents(s: UnsubcriptionEvent) {
214
- const allTopics = this.programs
215
- .map((x) => x.getTopics?.())
216
- .filter((x) => x)
217
- .flat() as string[];
218
-
219
- // if subscribing not subscribing to any topics, emit "leave" event
220
- for (const topic of allTopics) {
221
- if (
222
- this.node.services.pubsub.getSubscribers(topic)?.has(s.from.hashcode())
223
- ) {
224
- return;
225
- }
226
- }
227
- this.events.dispatchEvent(new CustomEvent("leave", { detail: s.from }));
228
- }
229
-
230
- private _subscriptionEventListener: (
231
- e: CustomEvent<SubscriptionEvent>
232
- ) => void;
233
- private _unsubscriptionEventListener: (
234
- e: CustomEvent<UnsubcriptionEvent>
235
- ) => void;
236
-
237
- private async processEnd(type: "drop" | "close") {
238
- if (!this.closed) {
239
- this.emitEvent(new CustomEvent(type, { detail: this }), true);
240
- if (type === "close") {
241
- this._eventOptions?.onClose?.(this);
242
- } else if (type === "drop") {
243
- this._eventOptions?.onDrop?.(this);
244
- } else {
245
- throw new Error("Unsupported event type: " + type);
246
- }
247
-
248
- const promises: Promise<void | boolean>[] = [];
249
-
250
- if (this.children) {
251
- for (const program of this.children) {
252
- promises.push(program[type](this as AbstractProgram)); // TODO types
253
- }
254
- this.children = [];
255
- }
256
- await Promise.all(promises);
257
-
258
- this._clear();
259
- this.closed = true;
260
- return true;
261
- } else {
262
- this._clear();
263
- return true;
264
- }
265
- }
266
-
267
- private async end(
268
- type: "drop" | "close",
269
- from?: AbstractProgram
270
- ): Promise<boolean> {
271
- if (this.closed) {
272
- return true;
273
- }
274
-
275
- let parentIdx = -1;
276
- let close = true;
277
- if (this.parents) {
278
- parentIdx = this.parents.findIndex((x) => x == from);
279
- if (parentIdx !== -1) {
280
- if (this.parents.length === 1) {
281
- close = true;
282
- } else {
283
- this.parents.splice(parentIdx, 1);
284
- close = false;
285
- }
286
- } else if (from) {
287
- throw new Error("Could not find from in parents");
288
- }
289
- }
290
-
291
- const end = close && (await this.processEnd(type));
292
- if (end) {
293
- this.node?.services.pubsub.removeEventListener(
294
- "subscribe",
295
- this._subscriptionEventListener
296
- );
297
- this.node?.services.pubsub.removeEventListener(
298
- "unsubscribe",
299
- this._unsubscriptionEventListener
300
- );
301
-
302
- this._eventOptions = undefined;
303
-
304
- if (parentIdx !== -1) {
305
- this.parents.splice(parentIdx, 1); // We splice this here because this._end depends on this parent to exist
306
- }
307
- }
308
-
309
- return end;
310
- }
311
- async close(from?: AbstractProgram): Promise<boolean> {
312
- return this.end("close", from);
313
- }
314
-
315
- async drop(from?: AbstractProgram): Promise<boolean> {
316
- return this.end("drop", from);
317
- }
318
-
319
- emitEvent(event: CustomEvent, parents = false) {
320
- this.events.dispatchEvent(event);
321
- if (parents) {
322
- if (this.parents) {
323
- for (const parent of this.parents) {
324
- parent?.emitEvent(event);
325
- }
326
- }
327
- }
328
- }
329
-
330
- /**
331
- * Wait for another peer to be 'ready' to talk with you for this particular program
332
- * @param other
333
- */
334
- async waitFor(...other: (PublicSignKey | Libp2pPeerId)[]): Promise<void> {
335
- const expectedHashes = new Set(
336
- other.map((x) =>
337
- x instanceof PublicSignKey
338
- ? x.hashcode()
339
- : getPublicKeyFromPeerId(x).hashcode()
340
- )
341
- );
342
- await waitForAsync(
343
- async () => {
344
- return (
345
- intersection(expectedHashes, await this.getReady()).size ===
346
- expectedHashes.size
347
- );
348
- },
349
- { delayInterval: 200, timeout: 10 * 1000 }
350
- ); // 200 ms delay since this is an expensive op. TODO, make event based instead
351
- }
352
-
353
- async getReady(): Promise<Set<string>> {
354
- // all peers that subscribe to all topics
355
- let ready: Set<string> | undefined = undefined; // the interesection of all ready
356
- for (const program of this.allPrograms) {
357
- if (program.getTopics) {
358
- const topics = program.getTopics();
359
- for (const topic of topics) {
360
- const subscribers = await this.node.services.pubsub.getSubscribers(
361
- topic
362
- );
363
- if (!subscribers) {
364
- throw new Error(
365
- "client is not subscriber to topic data, do not have any info about peer readiness"
366
- );
367
- }
368
- ready = intersection(ready, subscribers.keys());
369
- }
370
- }
371
- }
372
- if (ready == null) {
373
- throw new Error("Do not have any info about peer readiness");
374
- }
375
- return ready;
376
- }
377
-
378
- get allPrograms(): AbstractProgram[] {
379
- if (this._allPrograms) {
380
- return this._allPrograms;
381
- }
382
- const arr: AbstractProgram[] = this.programs;
383
- const nexts = this.programs;
384
- for (const next of nexts) {
385
- arr.push(...next.allPrograms);
386
- }
387
- this._allPrograms = arr;
388
- return this._allPrograms;
389
- }
390
-
391
- get programs(): AbstractProgram[] {
392
- return getValuesWithType(this, AbstractProgram);
393
- }
394
-
395
- clone(): this {
396
- return deserialize(serialize(this), this.constructor);
397
- }
398
-
399
- getTopics?(): string[];
400
- }
401
-
402
- export interface CanTrust {
403
- isTrusted(keyHash: string): Promise<boolean> | boolean;
404
- }
405
-
406
- @variant(0)
407
- export abstract class Program<
408
- Args = any,
409
- Events extends ProgramEvents = ProgramEvents
410
- >
411
- extends AbstractProgram<Args, Events>
412
- implements Addressable, Saveable
413
- {
414
- private _address?: Address;
415
-
416
- constructor() {
417
- super();
418
- }
419
-
420
- get address(): Address {
421
- if (!this._address) {
422
- throw new Error(
423
- "Address does not exist, please open or save this program once to obtain it"
424
- );
425
- }
426
- return this._address;
427
- }
428
-
429
- set address(address: Address) {
430
- this._address = address;
431
- }
432
-
433
- async beforeOpen(
434
- node: ProgramClient,
435
- options?: ProgramInitializationOptions<Args>
436
- ) {
437
- // check that a discriminator exist
438
- const schema = getSchema(this.constructor);
439
- if (!schema || typeof schema.variant !== "string") {
440
- throw new Error(
441
- `Expecting class to be decorated with a string variant. Example:\n\'import { variant } "@dao-xyz/borsh"\n@variant("example-db")\nclass ${this.constructor.name} { ...`
442
- );
443
- }
444
-
445
- await this.save(node.services.blocks);
446
- if (getAllParentAddresses(this as AbstractProgram).includes(this.address)) {
447
- throw new Error(
448
- "Subprogram has same address as some parent program. This is not currently supported"
449
- );
450
- }
451
- return super.beforeOpen(node, options);
452
- }
453
-
454
- static async open<T extends Program<Args>, Args = any>(
455
- this: Constructor<T>,
456
- address: Address,
457
- node: ProgramClient,
458
- options?: ProgramInitializationOptions<Args>
459
- ): Promise<T> {
460
- const p = await Program.load<T>(address, node.services.blocks);
461
-
462
- if (!p) {
463
- throw new Error("Failed to load program");
464
- }
465
- await node.open(p, options);
466
- return p as T;
467
- }
468
- async save(store: Blocks = this.node.services.blocks): Promise<Address> {
469
- const existingAddress = this._address;
470
- const hash = await store.put(serialize(this));
471
-
472
- this._address = hash;
473
- if (!this.address) {
474
- throw new Error("Unexpected");
475
- }
476
-
477
- if (existingAddress && existingAddress !== this.address) {
478
- throw new Error(
479
- "Program properties has been changed after constructor so that the hash has changed. Make sure that the 'setup(...)' function does not modify any properties that are to be serialized"
480
- );
481
- }
482
-
483
- return this._address!;
484
- }
485
-
486
- async delete(): Promise<void> {
487
- if (this.address) {
488
- return this.node.services.blocks.rm(this.address);
489
- }
490
- // Not saved
491
- }
492
-
493
- static async load<P extends Program<any>>(
494
- address: Address,
495
- store: Blocks,
496
- options?: {
497
- timeout?: number;
498
- }
499
- ): Promise<P | undefined> {
500
- const bytes = await store.get(address, options);
501
- if (!bytes) {
502
- return undefined;
503
- }
504
- const der = deserialize(bytes, Program);
505
- der.address = address;
506
- return der as P;
507
- }
508
-
509
- async drop(from?: AbstractProgram): Promise<boolean> {
510
- const dropped = await super.drop(from);
511
- if (!dropped) {
512
- return dropped;
513
- }
514
- await this.delete();
515
- return true;
516
- }
517
- }
518
-
519
- /**eve
520
- * Building block, but not something you use as a standalone
521
- */
522
- @variant(1)
523
- export abstract class ComposableProgram<
524
- Args = any,
525
- Events extends ProgramEvents = ProgramEvents
526
- > extends AbstractProgram<Args, Events> {}
1
+ export {
2
+ type ProgramInitializationOptions,
3
+ type OpenOptions,
4
+ } from "./handler.js";
5
+ export * from "./client.js";
6
+ export * from "./program.js";
7
+ export * from "./address.js";