-
Notifications
You must be signed in to change notification settings - Fork 73
Expand file tree
/
Copy pathindirecting.py
More file actions
1291 lines (1030 loc) · 45.1 KB
/
indirecting.py
File metadata and controls
1291 lines (1030 loc) · 45.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- encoding: utf-8 -*-
"""
KERI
keri.app.indirecting module
simple indirect mode demo support classes
"""
import datetime
import platform
import falcon
import time
import sys
import traceback
from ordered_set import OrderedSet as oset
from hio.base import doing
from hio.core import http, tcp
from hio.core.tcp import serving
from hio.help import decking
import keri.app.oobiing
from . import directing, storing, httping, forwarding, agenting, oobiing
from ..metric import EscrowEnd
from .habbing import GroupHab
from .. import help, kering
from ..core import (eventing, parsing, routing, coring, serdering,
Counter, Codens)
from ..core.coring import Ilks
from ..db import basing, dbing
from ..end import ending
from ..help import helping
from ..peer import exchanging
from ..vdr import verifying, viring
from ..vdr.eventing import Tevery
logger = help.ogler.getLogger()
def setupWitness(hby, alias="witness", mbx=None, aids=None, tcpPort=5631, httpPort=5632,
keypath=None, certpath=None, cafilepath=None):
"""
Setup witness controller and doers
"""
host = "0.0.0.0"
if platform.system() == "Windows":
host = "127.0.0.1"
cues = decking.Deck()
doers = []
# make hab
hab = hby.habByName(name=alias)
if hab is None:
hab = hby.makeHab(name=alias, transferable=False)
reger = viring.Reger(name=hab.name, db=hab.db, temp=False)
verfer = verifying.Verifier(hby=hby, reger=reger)
mbx = mbx if mbx is not None else storing.Mailboxer(name=alias, temp=hby.temp)
forwarder = forwarding.ForwardHandler(hby=hby, mbx=mbx)
exchanger = exchanging.Exchanger(hby=hby, handlers=[forwarder])
clienter = httping.Clienter()
oobiery = keri.app.oobiing.Oobiery(hby=hby, clienter=clienter)
app = falcon.App(cors_enable=True)
ending.loadEnds(app=app, hby=hby, default=hab.pre)
oobiing.loadEnds(app=app, hby=hby, prefix="/ext")
rep = storing.Respondant(hby=hby, mbx=mbx, aids=aids)
rvy = routing.Revery(db=hby.db, cues=cues)
kvy = eventing.Kevery(db=hby.db,
lax=True,
local=False,
rvy=rvy,
cues=cues)
kvy.registerReplyRoutes(router=rvy.rtr)
tvy = Tevery(reger=verfer.reger,
db=hby.db,
local=False,
cues=cues)
tvy.registerReplyRoutes(router=rvy.rtr)
parser = parsing.Parser(framed=True,
kvy=kvy,
tvy=tvy,
exc=exchanger,
rvy=rvy)
httpEnd = HttpEnd(rxbs=parser.ims, mbx=mbx)
app.add_route("/", httpEnd)
receiptEnd = ReceiptEnd(hab=hab, inbound=cues, aids=aids)
app.add_route("/receipts", receiptEnd)
queryEnd = QueryEnd(hab=hab, reger=reger)
app.add_route("/query", queryEnd)
metricsEnd = EscrowEnd(hby=hby, reger=reger)
app.add_route("/metrics", metricsEnd)
server = createHttpServer(host, httpPort, app, keypath, certpath, cafilepath)
if not server.reopen():
raise RuntimeError(f"cannot create http server on port {httpPort}")
httpServerDoer = http.ServerDoer(server=server)
# setup doers
regDoer = basing.BaserDoer(baser=reger)
if tcpPort is not None:
server = serving.Server(host="", port=tcpPort)
if not server.reopen():
raise RuntimeError(f"cannot create tcp server on port {tcpPort}")
serverDoer = serving.ServerDoer(server=server)
directant = directing.Directant(hab=hab, server=server, verifier=verfer)
doers.extend([directant, serverDoer])
witStart = WitnessStart(hab=hab, parser=parser, cues=receiptEnd.outbound,
kvy=kvy, tvy=tvy, rvy=rvy, exc=exchanger, replies=rep.reps,
responses=rep.cues, queries=httpEnd.qrycues)
doers.extend([regDoer, httpServerDoer, rep, witStart, receiptEnd, *oobiery.doers])
return doers
def createHttpServer(host, port, app, keypath=None, certpath=None, cafilepath=None):
"""
Create an HTTP or HTTPS server depending on whether TLS key material is present
Parameters:
host(str) : host to bind to for this server, or None for default of '0.0.0.0', all ifaces
port (int) : port to listen on for all HTTP(s) server instances
app (Any) : WSGI application instance to pass to the http.Server instance
keypath (string) : the file path to the TLS private key
certpath (string) : the file path to the TLS signed certificate (public key)
cafilepath (string): the file path to the TLS CA certificate chain file
Returns:
hio.core.http.Server
"""
if keypath is not None and certpath is not None and cafilepath is not None:
servant = tcp.ServerTls(certify=False,
keypath=keypath,
certpath=certpath,
cafilepath=cafilepath,
port=port)
server = http.Server(host=host, port=port, app=app, servant=servant)
else:
server = http.Server(host=host, port=port, app=app)
return server
class WitnessStart(doing.DoDoer):
""" Doer to print witness prefix after initialization
"""
def __init__(self, hab, parser, kvy, tvy, rvy, exc, cues=None, replies=None, responses=None, queries=None, **opts):
self.hab = hab
self.parser = parser
self.kvy = kvy
self.tvy = tvy
self.rvy = rvy
self.exc = exc
self.queries = queries if queries is not None else decking.Deck()
self.replies = replies if replies is not None else decking.Deck()
self.responses = responses if responses is not None else decking.Deck()
self.cues = cues if cues is not None else decking.Deck()
doers = [doing.doify(self.start), doing.doify(self.msgDo), doing.doify(self.escrowDo), doing.doify(self.cueDo)]
super().__init__(doers=doers, **opts)
def start(self, tymth=None, tock=0.0, **kwa):
""" Prints witness name and prefix
Parameters:
tymth (function): injected function wrapper closure returned by .tymen() of
Tymist instance. Calling tymth() returns associated Tymist .tyme.
tock (float): injected initial tock value
"""
self.wind(tymth)
self.tock = tock
_ = (yield self.tock)
while not self.hab.inited:
yield self.tock
print("Witness", self.hab.name, ":", self.hab.pre)
def msgDo(self, tymth=None, tock=0.0, **kwa):
"""
Returns doifiable Doist compatibile generator method (doer dog) to process
incoming message stream of .kevery
Parameters:
tymth (function): injected function wrapper closure returned by .tymen() of
Tymist instance. Calling tymth() returns associated Tymist .tyme.
tock (float): injected initial tock value
Usage:
add result of doify on this method to doers list
"""
self.wind(tymth)
self.tock = tock
_ = (yield self.tock)
if self.parser.ims:
logger.debug("Client %s received:\n%s\n...\n", self.kvy, self.parser.ims[:1024])
done = yield from self.parser.parsator(local=True) # process messages continuously
return done # should nover get here except forced close
def escrowDo(self, tymth=None, tock=0.0, **kwa):
"""
Returns doifiable Doist compatibile generator method (doer dog) to process
.kevery and .tevery escrows.
Parameters:
tymth (function): injected function wrapper closure returned by .tymen() of
Tymist instance. Calling tymth() returns associated Tymist .tyme.
tock (float): injected initial tock value
Usage:
add result of doify on this method to doers list
"""
self.wind(tymth)
self.tock = tock
_ = (yield self.tock)
while True:
self.kvy.processEscrows()
self.rvy.processEscrowReply()
if self.tvy is not None:
self.tvy.processEscrows()
self.exc.processEscrow()
yield
def cueDo(self, tymth=None, tock=0.0, **kwa):
"""
Returns doifiable Doist compatibile generator method (doer dog) to process
.kevery.cues deque
Doist Injected Attributes:
g.tock = tock # default tock attributes
g.done = None # default done state
g.opts
Parameters:
tymth is injected function wrapper closure returned by .tymen() of
Tymist instance. Calling tymth() returns associated Tymist .tyme.
tock is injected initial tock value
Usage:
add result of doify on this method to doers list
"""
self.wind(tymth)
self.tock = tock
_ = (yield self.tock)
while True:
while self.cues:
cue = self.cues.pull() # self.cues.popleft()
cueKin = cue["kin"]
if cueKin == "stream":
self.queries.append(cue)
else:
self.responses.append(cue)
yield self.tock
yield self.tock
class Indirector(doing.DoDoer):
"""
Base class for Indirect Mode KERI Controller Doer with habitat and
TCP Clients for talking to witnesses
Subclass of DoDoer with doers list from do generator methods:
.msgDo, .cueDo, and .escrowDo.
Enables continuous scheduling of doers (do generator instances or functions)
Implements Doist like functionality to allow nested scheduling of doers.
Each DoDoer runs a list of doers like a Doist but using the tyme from its
injected tymist as injected by its parent DoDoer or Doist.
Scheduling hierarchy: Doist->DoDoer...->DoDoer->Doers
Attributes:
.done is Boolean completion state:
True means completed
Otherwise incomplete. Incompletion maybe due to close or abort.
.opts is dict of injected options for its generator .do
.doers is list of Doers or Doer like generator functions
Attributes:
hab (Habitat: local controller's context
client (serving.Client): hio TCP client instance.
Assumes operated by another doer.
Properties:
tyme (float): relative cycle time of associated Tymist, obtained
via injected .tymth function wrapper closure.
tymth (function): function wrapper closure returned by Tymist .tymeth()
method. When .tymth is called it returns associated Tymist .tyme.
.tymth provides injected dependency on Tymist tyme base.
tock (float): desired time in seconds between runs or until next run,
non negative, zero means run asap
Methods:
.wind injects ._tymth dependency from associated Tymist to get its .tyme
.__call__ makes instance callable
Appears as generator function that returns generator
.do is generator method that returns generator
.enter is enter context action method
.recur is recur context action method or generator method
.clean is clean context action method
.exit is exit context method
.close is close context method
.abort is abort context method
Hidden:
._tymth is injected function wrapper closure returned by .tymen() of
associated Tymist instance that returns Tymist .tyme. when called.
._tock is hidden attribute for .tock property
"""
def __init__(self, hab, client, direct=True, doers=None, **kwa):
"""
Initialize instance.
Inherited Parameters:
tymist is Tymist instance
tock is float seconds initial value of .tock
doers is list of doers (do generator instances, functions or methods)
Parameters:
hab is Habitat instance of local controller's context
client is TCP Client instance
direct is Boolean, True means direwct mode process cured receipts
False means indirect mode don't process cue'ed receipts
"""
self.hab = hab
self.client = client # use client for both rx and tx
self.direct = True if direct else False
self.kevery = eventing.Kevery(db=self.hab.db,
lax=False,
local=False,
cloned=not self.direct,
direct=self.direct)
self.parser = parsing.Parser(ims=self.client.rxbs,
framed=True,
kvy=self.kevery)
doers = doers if doers is not None else []
doers.extend([doing.doify(self.msgDo),
doing.doify(self.escrowDo)])
if self.direct:
doers.extend([doing.doify(self.cueDo)])
super(Indirector, self).__init__(doers=doers, **kwa)
if self.tymth:
self.client.wind(self.tymth)
def wind(self, tymth):
"""
Inject new tymist.tymth as new ._tymth. Changes tymist.tyme base.
Updates winds .tymer .tymth
"""
super(Indirector, self).wind(tymth)
self.client.wind(tymth)
def msgDo(self, tymth=None, tock=0.0, **kwa):
"""
Returns doifiable Doist compatibile generator method (doer dog) to process
incoming message stream of .kevery
Doist Injected Attributes:
g.tock = tock # default tock attributes
g.done = None # default done state
g.opts
Parameters:
tymth is injected function wrapper closure returned by .tymen() of
Tymist instance. Calling tymth() returns associated Tymist .tyme.
tock is injected initial tock value
Usage:
add result of doify on this method to doers list
"""
self.wind(tymth)
self.tock = tock
_ = (yield self.tock)
if self.parser.ims:
logger.debug("Client %s received:\n%s\n...\n", self.hab.pre, self.parser.ims[:1024])
done = yield from self.parser.parsator(local=True) # process messages continuously
return done # should nover get here except forced close
def cueDo(self, tymth=None, tock=0.0, **kwa):
"""
Returns doifiable Doist compatibile generator method (doer dog) to process
.kevery.cues deque
Doist Injected Attributes:
g.tock = tock # default tock attributes
g.done = None # default done state
g.opts
Parameters:
tymth is injected function wrapper closure returned by .tymen() of
Tymist instance. Calling tymth() returns associated Tymist .tyme.
tock is injected initial tock value
Usage:
add result of doify on this method to doers list
"""
self.wind(tymth)
self.tock = tock
_ = (yield self.tock)
while True:
for msg in self.hab.processCuesIter(self.kevery.cues):
self.sendMessage(msg, label="chit or receipt")
yield # throttle just do one cue at a time
yield
def escrowDo(self, tymth=None, tock=0.0, **kwa):
"""
Returns doifiable Doist compatibile generator method (doer dog) to process
.kevery escrows.
Doist Injected Attributes:
g.tock = tock # default tock attributes
g.done = None # default done state
g.opts
Parameters:
tymth is injected function wrapper closure returned by .tymen() of
Tymist instance. Calling tymth() returns associated Tymist .tyme.
tock is injected initial tock value
Usage:
add result of doify on this method to doers list
"""
self.wind(tymth)
self.tock = tock
_ = (yield self.tock)
while True:
self.kevery.processEscrows()
yield
def sendMessage(self, msg, label=""):
"""
Sends message msg and loggers label if any
"""
self.client.tx(msg) # send to remote
logger.debug("%s sent %s:\n%s\n\n", self.hab.pre, label, bytes(msg))
class MailboxDirector(doing.DoDoer):
"""
Class for Indirect Mode KERI Controller Doer with habitat and
TCP Clients for talking to witnesses
Subclass of DoDoer with doers list from do generator methods:
.msgDo, .cueDo, and .escrowDo.
Enables continuous scheduling of doers (do generator instances or functions)
Implements Doist like functionality to allow nested scheduling of doers.
Each DoDoer runs a list of doers like a Doist but using the tyme from its
injected tymist as injected by its parent DoDoer or Doist.
Scheduling hierarchy: Doist->DoDoer...->DoDoer->Doers
Attributes:
.done is Boolean completion state:
True means completed
Otherwise incomplete. Incompletion maybe due to close or abort.
.opts is dict of injected options for its generator .do
.doers is list of Doers or Doer like generator functions
Attributes:
hby (Habitat: local controller's context
Properties:
hby (Habery): the Habery in which mailbox messages are routed
verifier (Verifier): TEL event acceptor and validator
exchanger (Exchanger): Exchange (exn) message delivery component
rep (Respondant): Respondant for reply messages
cues (Deck): Queue for new actions to schedule shared between the Revery, Kevery (and Kever), and Tevery (and Tever)
Methods:
.wind injects ._tymth dependency from associated Tymist to get its .tyme
.__call__ makes instance callable
Appears as generator function that returns generator
.do is generator method that returns generator
.enter is enter context action method
.recur is recur context action method or generator method
.clean is clean context action method
.exit is exit context method
.close is close context method
.abort is abort context method
Hidden:
._tymth is injected function wrapper closure returned by .tymen() of
associated Tymist instance that returns Tymist .tyme. when called.
._tock is hidden attribute for .tock property
"""
def __init__(self, hby, topics, ims=None, verifier=None, kvy=None, exc=None, rep=None, cues=None, rvy=None,
tvy=None, witnesses=True, **kwa):
"""
Initialize instance.
Inherited Parameters:
tymist is Tymist instance
tock is float seconds initial value of .tock
doers is list of doers (do generator instances, functions or methods)
Parameters:
hab is Habitat instance of local controller's context
client is TCP Client instance
direct is Boolean, True means direwct mode process cured receipts
False means indirect mode don't process cue'ed receipts
"""
self.hby = hby
self.verifier = verifier
self.exchanger = exc
self.rep = rep
self.topics = topics
self.pollers = list()
self.prefixes = oset()
self.cues = cues if cues is not None else decking.Deck()
self.witnesses = witnesses
self.ims = ims if ims is not None else bytearray()
doers = []
doers.extend([doing.doify(self.pollDo),
doing.doify(self.msgDo),
doing.doify(self.escrowDo)])
self.rtr = routing.Router()
self.rvy = rvy if rvy is not None else routing.Revery(db=self.hby.db, rtr=self.rtr, cues=cues,
lax=True, local=False)
# needs unique kevery with ims per remoter connnection
self.kvy = kvy if kvy is not None else eventing.Kevery(db=self.hby.db,
cues=self.cues,
rvy=self.rvy,
lax=True,
local=False,
direct=False)
self.kvy.registerReplyRoutes(self.rtr)
if self.verifier is not None:
self.tvy = tvy if tvy is not None else Tevery(reger=self.verifier.reger,
db=self.hby.db, rvy=self.rvy,
lax=True, local=False, cues=self.cues)
self.tvy.registerReplyRoutes(self.rtr)
else:
self.tvy = None
self.parser = parsing.Parser(ims=self.ims,
framed=True,
kvy=self.kvy,
tvy=self.tvy,
exc=self.exchanger,
rvy=self.rvy,
vry=self.verifier)
super(MailboxDirector, self).__init__(doers=doers, **kwa)
def wind(self, tymth):
"""
Inject new tymist.tymth as new ._tymth. Changes tymist.tyme base.
Updates winds .tymer .tymth
"""
super(MailboxDirector, self).wind(tymth)
def pollDo(self, tymth=None, tock=0.0, **kwa):
"""
Returns:
doifiable Doist compatible generator method
Usage:
add result of doify on this method to doers list
"""
# enter context
self.wind(tymth)
self.tock = tock
_ = (yield self.tock)
habs = list(self.hby.habs.values())
for hab in habs:
if hab.accepted:
self.addPollers(hab)
_ = (yield self.tock)
while True:
pres = oset(self.hby.habs.keys())
if new := pres - self.prefixes:
for pre in new:
hab = self.hby.habs[pre]
if hab.accepted:
self.addPollers(hab=hab)
_ = (yield self.tock)
for msg in self.processPollIter():
self.ims.extend(msg)
_ = (yield self.tock)
_ = (yield self.tock)
def addPollers(self, hab):
""" add mailbox pollers for every witness for this prefix identifier
Parameters:
hab (Hab): the Hab of the prefix
"""
for (_, erole, eid), end in hab.db.ends.getItemIter(keys=(hab.pre, kering.Roles.mailbox)):
if end.allowed:
poller = Poller(hab=hab, topics=self.topics, witness=eid)
self.pollers.append(poller)
self.extend([poller])
if self.witnesses:
wits = hab.kever.wits
for wit in wits:
poller = Poller(hab=hab, topics=self.topics, witness=wit)
self.pollers.append(poller)
self.extend([poller])
self.prefixes.add(hab.pre)
def addPoller(self, hab, witness):
poller = Poller(hab=hab, topics=self.topics, witness=witness)
self.pollers.append(poller)
self.extend([poller])
def processPollIter(self):
"""
Iterate through cues and yields one or more responses for each cue.
Parameters:
cues is deque of cues
"""
mail = []
for poller in self.pollers: # get responses from all behaviors
while poller.msgs:
msg = poller.msgs.popleft()
mail.append(msg)
while mail: # iteratively process each response in responses
msg = mail.pop(0)
yield msg
def msgDo(self, tymth=None, tock=0.0, **kwa):
"""
Returns doifiable Doist compatibile generator method (doer dog) to process
incoming message stream of .kevery
Doist Injected Attributes:
g.tock = tock # default tock attributes
g.done = None # default done state
g.opts
Parameters:
tymth is injected function wrapper closure returned by .tymen() of
Tymist instance. Calling tymth() returns associated Tymist .tyme.
tock is injected initial tock value
Usage:
add result of doify on this method to doers list
"""
self.wind(tymth)
self.tock = tock
_ = (yield self.tock)
done = yield from self.parser.parsator(local=True) # process messages continuously
return done # should nover get here except forced close
def escrowDo(self, tymth=None, tock=0.0, **kwa):
"""
Returns doifiable Doist compatibile generator method (doer dog) to process
.kevery escrows.
Doist Injected Attributes:
g.tock = tock # default tock attributes
g.done = None # default done state
g.opts
Parameters:
tymth is injected function wrapper closure returned by .tymen() of
Tymist instance. Calling tymth() returns associated Tymist .tyme.
tock is injected initial tock value
Usage:
add result of doify on this method to doers list
"""
self.wind(tymth)
self.tock = tock
_ = (yield self.tock)
while True:
self.kvy.processEscrows()
self.rvy.processEscrowReply()
if self.exchanger is not None:
self.exchanger.processEscrow()
if self.tvy is not None:
self.tvy.processEscrows()
if self.verifier is not None:
self.verifier.processEscrows()
yield
@property
def times(self):
times = dict()
for poller in self.pollers: # get responses from all pollers
times |= poller.times
return times
class Poller(doing.DoDoer):
"""
Polls remote SSE endpoint for event that are KERI messages to be processed
"""
def __init__(self, hab, witness, topics, msgs=None, retry=1000, **kwa):
"""
Returns doist compatible doing.Doer that polls a witness for mailbox messages
as SSE events
Parameters:
hab:
witness:
topics:
msgs:
"""
self.hab = hab
self.pre = hab.pre
self.witness = witness
self.topics = topics
self.retry = retry
self.msgs = None if msgs is not None else decking.Deck()
self.times = dict()
doers = [doing.doify(self.eventDo)]
super(Poller, self).__init__(doers=doers, **kwa)
def eventDo(self, tymth=None, tock=0.0, **kwa):
"""
Returns:
doifiable Doist compatible generator method
Usage:
add result of doify on this method to doers list
"""
self.wind(tymth)
self.tock = tock
_ = (yield self.tock)
witrec = self.hab.db.tops.get((self.pre, self.witness))
if witrec is None:
witrec = basing.TopicsRecord(topics=dict())
while self.retry > 0:
try:
client, clientDoer = agenting.httpClient(self.hab, self.witness)
except kering.MissingEntryError as e:
traceback.print_exception(e, file=sys.stderr) # logging
yield self.tock
continue
self.extend([clientDoer])
topics = dict()
q = dict(pre=self.pre, topics=topics)
for topic in self.topics:
if topic in witrec.topics:
topics[topic] = witrec.topics[topic] + 1
else:
topics[topic] = 0
if isinstance(self.hab, GroupHab):
msg = self.hab.mhab.query(pre=self.pre, src=self.witness, route="mbx", query=q)
else:
msg = self.hab.query(pre=self.pre, src=self.witness, route="mbx", query=q)
httping.createCESRRequest(msg, client, dest=self.witness)
while client.requests:
yield self.tock
created = helping.nowUTC()
while True:
now = helping.nowUTC()
if now - created > datetime.timedelta(seconds=30):
self.remove([clientDoer])
break
while client.events:
evt = client.events.popleft()
if "retry" in evt:
self.retry = evt["retry"]
if "id" not in evt or "data" not in evt or "name" not in evt:
logger.error(f"bad mailbox event: {evt}")
continue
idx = evt["id"]
msg = evt["data"]
tpc = evt["name"]
if not idx or not msg or not tpc:
logger.error(f"bad mailbox event: {evt}")
continue
self.msgs.append(msg.encode("utf=8"))
yield self.tock
witrec.topics[tpc] = int(idx)
self.times[tpc] = helping.nowUTC()
self.hab.db.tops.pin((self.pre, self.witness), witrec)
yield 0.25
yield self.retry / 1000
class HttpEnd:
"""
HTTP handler that accepts and KERI events POSTed as the body of a request with all attachments to
the message as a CESR attachment HTTP header. KEL Messages are processed and added to the database
of the provided Habitat.
This also handles `req`, `exn` and `tel` messages that respond with a KEL replay.
"""
TimeoutQNF = 30
TimeoutMBX = 5
def __init__(self, rxbs=None, mbx=None, qrycues=None):
"""
Create the KEL HTTP server from the Habitat with an optional Falcon App to
register the routes with.
Parameters
rxbs (bytearray): output queue of bytes for message processing
mbx (Mailboxer): Mailbox storage
qrycues (Deck): inbound qry response queues
"""
self.rxbs = rxbs if rxbs is not None else bytearray()
self.mbx = mbx
self.qrycues = qrycues if qrycues is not None else decking.Deck()
def on_post(self, req, rep):
"""
Handles POST for KERI event messages.
Parameters:
req (Request) Falcon HTTP request
rep (Response) Falcon HTTP response
---
summary: Accept KERI events with attachment headers and parse
description: Accept KERI events with attachment headers and parse.
tags:
- Events
requestBody:
required: true
content:
application/json:
schema:
type: object
description: KERI event message
responses:
200:
description: Mailbox query response for server sent events
204:
description: KEL or EXN event accepted.
"""
if req.method == "OPTIONS":
rep.status = falcon.HTTP_200
return
rep.set_header('Cache-Control', "no-cache")
rep.set_header('connection', "close")
cr = httping.parseCesrHttpRequest(req=req)
sadder = coring.Sadder(ked=cr.payload, kind=eventing.Kinds.json)
msg = bytearray(sadder.raw)
msg.extend(cr.attachments.encode("utf-8"))
self.rxbs.extend(msg)
if sadder.proto in ("ACDC",):
rep.set_header('Content-Type', "application/json")
rep.status = falcon.HTTP_204
else:
ilk = sadder.ked["t"]
if ilk in (Ilks.icp, Ilks.rot, Ilks.ixn, Ilks.dip, Ilks.drt, Ilks.exn, Ilks.rpy):
rep.set_header('Content-Type', "application/json")
rep.status = falcon.HTTP_204
elif ilk in (Ilks.vcp, Ilks.vrt, Ilks.iss, Ilks.rev, Ilks.bis, Ilks.brv):
rep.set_header('Content-Type', "application/json")
rep.status = falcon.HTTP_204
elif ilk in (Ilks.qry,):
if sadder.ked["r"] in ("mbx",):
rep.set_header('Content-Type', "text/event-stream")
rep.status = falcon.HTTP_200
rep.stream = QryRpyMailboxIterable(mbx=self.mbx, cues=self.qrycues, said=sadder.said)
else:
rep.set_header('Content-Type', "application/json")
rep.status = falcon.HTTP_204
def on_put(self, req, rep):
"""
Handles PUT for KERI mbx event messages.
Parameters:
req (Request) Falcon HTTP request
rep (Response) Falcon HTTP response
---
summary: Accept KERI events with attachment headers and parse
description: Accept KERI events with attachment headers and parse.
tags:
- Events
requestBody:
required: true
content:
application/json:
schema:
type: object
description: KERI event message
responses:
200:
description: Mailbox query response for server sent events
204:
description: KEL or EXN event accepted.
"""
if req.method == "OPTIONS":
rep.status = falcon.HTTP_200
return
rep.set_header('Cache-Control', "no-cache")
rep.set_header('connection', "close")
self.rxbs.extend(req.bounded_stream.read())
rep.set_header('Content-Type', "application/json")
rep.status = falcon.HTTP_204
class QryRpyMailboxIterable:
def __init__(self, cues, mbx, said, retry=5000):
self.mbx = mbx
self.retry = retry
self.cues = cues
self.said = said
self.iter = None
def __iter__(self):
return self
def __next__(self):
if self.iter is None:
if self.cues:
cue = self.cues.pull()
serder = cue["serder"]
if serder.said == self.said:
kin = cue["kin"]
if kin == "stream":
self.iter = iter(MailboxIterable(mbx=self.mbx, pre=cue["pre"], topics=cue["topics"],
retry=self.retry))
else:
self.cues.append(cue)
return b''
return next(self.iter)
class MailboxIterable:
TimeoutMBX = 30000000
def __init__(self, mbx, pre, topics, retry=5000):