Check-in [fac5762bd4]
Not logged in

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Release of mecate 1.2.1. Minor clean up to remove extraneous debut print out.
Timelines: family | ancestors | descendants | both | trunk | mecate-1.2.1
Files: files | file ages | folders
SHA1: fac5762bd4714cdcc1ac20cbe1cd8e698021b382
User & Date: andrewm 2019-10-03 17:32:53
Context
2019-10-31
14:02
Release of bosal 1.2.2. This release corrects problems associated with access to attributes whose types are arrays. check-in: b72f8d3d94 user: andrewm tags: trunk, bosal-1.2.2
2019-10-03
17:32
Release of mecate 1.2.1. Minor clean up to remove extraneous debut print out. check-in: fac5762bd4 user: andrewm tags: trunk, mecate-1.2.1
17:28
Minor clean up of mecate to remove an extraneous "puts" debug printout and correct the version numbers on the man pages. check-in: 01434c3ba9 user: andrewm tags: micca-harness
2019-09-01
13:57
Update version number in man page. check-in: b380927484 user: andrewm tags: trunk, mecate-1.2
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Changes to mecate/code/tcl/teapot.txt.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Package mecate 1.2
Meta description Mecate is a package that provides a set of command to
Meta description interact with bosal generated test harnesses.
Meta entrysource mecate.tcl
Meta included    mecate.tcl
Meta platform    tcl
Meta require     {Tcl 8.6}
Meta require     logger
Meta require     oo::util
Meta require     ral
Meta require     ralutil
Meta require     struct::queue
Meta summary     Command interface to bosal generated test harnesses.

|













1
2
3
4
5
6
7
8
9
10
11
12
13
14
Package mecate 1.2.1
Meta description Mecate is a package that provides a set of command to
Meta description interact with bosal generated test harnesses.
Meta entrysource mecate.tcl
Meta included    mecate.tcl
Meta platform    tcl
Meta require     {Tcl 8.6}
Meta require     logger
Meta require     oo::util
Meta require     ral
Meta require     ralutil
Meta require     struct::queue
Meta summary     Command interface to bosal generated test harnesses.

Changes to mecate/doc/man/mecate.html.

93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
...
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
--></style>
</head>
<!-- Generated from file 'mecate.man' by tcllib/doctools with format 'html'
   -->
<!-- mecate.n
   -->
<body><div class="doctools">
<h1 class="doctools_title">mecate(n) 1.2 mecate &quot;Mecate Package for Bosal Test Harnesses&quot;</h1>
<div id="name" class="doctools_section"><h2><a name="name">Name</a></h2>
<p>mecate - Interacting with a bosal generated test harness</p>
</div>
<div id="toc" class="doctools_section"><h2><a name="toc">Table Of Contents</a></h2>
<ul class="doctools_toc">
<li class="doctools_section"><a href="#toc">Table Of Contents</a></li>
<li class="doctools_section"><a href="#synopsis">Synopsis</a></li>
................................................................................
<li class="doctools_section"><a href="#keywords">Keywords</a></li>
</ul>
</div>
<div id="synopsis" class="doctools_section"><h2><a name="synopsis">Synopsis</a></h2>
<div class="doctools_synopsis">
<ul class="doctools_requirements">
<li>package require <b class="pkgname">Tcl 8.6</b></li>
<li>package require <b class="pkgname">mecate <span class="opt">?1.2?</span></b></li>
</ul>
<ul class="doctools_syntax">
<li><a href="#1"><b class="cmd">mecate rein create</b> <i class="arg">reinobj</i> <i class="arg"><span class="opt">?options?</span></i></a></li>
<li><a href="#2"><b class="cmd">mecate rein new</b> <i class="arg"><span class="opt">?options?</span></i></a></li>
<li><a href="#3"><b class="cmd">mecate eventTraceFormat</b> <i class="arg">trace</i></a></li>
<li><a href="#4"><b class="cmd">mecate instrTraceFormat</b> <i class="arg">trace</i></a></li>
<li><a href="#5"><b class="cmd">mecate fatalTraceFormat</b> <i class="arg">trace</i></a></li>







|







 







|







93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
...
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
--></style>
</head>
<!-- Generated from file 'mecate.man' by tcllib/doctools with format 'html'
   -->
<!-- mecate.n
   -->
<body><div class="doctools">
<h1 class="doctools_title">mecate(n) 1.2.1 mecate &quot;Mecate Package for Bosal Test Harnesses&quot;</h1>
<div id="name" class="doctools_section"><h2><a name="name">Name</a></h2>
<p>mecate - Interacting with a bosal generated test harness</p>
</div>
<div id="toc" class="doctools_section"><h2><a name="toc">Table Of Contents</a></h2>
<ul class="doctools_toc">
<li class="doctools_section"><a href="#toc">Table Of Contents</a></li>
<li class="doctools_section"><a href="#synopsis">Synopsis</a></li>
................................................................................
<li class="doctools_section"><a href="#keywords">Keywords</a></li>
</ul>
</div>
<div id="synopsis" class="doctools_section"><h2><a name="synopsis">Synopsis</a></h2>
<div class="doctools_synopsis">
<ul class="doctools_requirements">
<li>package require <b class="pkgname">Tcl 8.6</b></li>
<li>package require <b class="pkgname">mecate <span class="opt">?1.2.1?</span></b></li>
</ul>
<ul class="doctools_syntax">
<li><a href="#1"><b class="cmd">mecate rein create</b> <i class="arg">reinobj</i> <i class="arg"><span class="opt">?options?</span></i></a></li>
<li><a href="#2"><b class="cmd">mecate rein new</b> <i class="arg"><span class="opt">?options?</span></i></a></li>
<li><a href="#3"><b class="cmd">mecate eventTraceFormat</b> <i class="arg">trace</i></a></li>
<li><a href="#4"><b class="cmd">mecate instrTraceFormat</b> <i class="arg">trace</i></a></li>
<li><a href="#5"><b class="cmd">mecate fatalTraceFormat</b> <i class="arg">trace</i></a></li>

Changes to mecate/doc/man/mecate.man.

1
2
3
4
5
6
7
8
[vset version 1.2]
[manpage_begin mecate n [vset version]]
[comment {
#
#*++
# PROJECT:
#   mecate
#
|







1
2
3
4
5
6
7
8
[vset version 1.2.1]
[manpage_begin mecate n [vset version]]
[comment {
#
#*++
# PROJECT:
#   mecate
#

Changes to mecate/doc/mecate.pdf.

cannot compute difference between binary files

Changes to mecate/src/Makefile.

5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# MODULE:
#
# ABSTRACT:
#
#*--
#

VERSION = 1.2

DOCDIR	= ../doc
CODEDIR	= ../code/tcl
TESTDIR = ../tests
PKGDIR	= ../../packages
MODDIR	= ../../modules








|







5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# MODULE:
#
# ABSTRACT:
#
#*--
#

VERSION = 1.2.1

DOCDIR	= ../doc
CODEDIR	= ../code/tcl
TESTDIR = ../tests
PKGDIR	= ../../packages
MODDIR	= ../../modules

Changes to mecate/src/mecate-docinfo.xml.

42
43
44
45
46
47
48








49
        Added method to accumulate options to control
        rendering of sequence diagrams.
        Incorporated code from John Wolfe to show state
        changes on the sequence diagram and to limit the
        swimlanes in the diagram to a set of named participants.
    </revremark>
  </revision>








</revhistory>







>
>
>
>
>
>
>
>

42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
        Added method to accumulate options to control
        rendering of sequence diagrams.
        Incorporated code from John Wolfe to show state
        changes on the sequence diagram and to limit the
        swimlanes in the diagram to a set of named participants.
    </revremark>
  </revision>
  <revision>
    <revnumber>1.2.1</revnumber>
    <date>October 2, 2019</date>
    <authorinitials>GAM</authorinitials>
    <revremark>
        Removed extraneous printout used for debugging.
    </revremark>
  </revision>
</revhistory>

Changes to mecate/src/mecate.aweb.

1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
....
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
....
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
    } else {
        set insts $participants
    }

    set extlabel BOUNDARY ;        # <1>
    <<seqDiag: declare participants>>

    puts "insts = [list $insts]"

    if {[dict get $seqDiagConfig -showstates]} {
        <<seqDiag: indicate initial state of each participant>>
    }

    set traces [pipe {
        rvajoin $traces [relvar set TransitionTrace] Transition |
        rvajoin ~ [relvar set PolymorphicTrace] Polymorphic |
................................................................................
    set logger [::logger::init mecate]
    set appenderType [expr {[dict exist [fconfigure stdout] -mode] ?\
            "colorConsole" : "console"}]
    ::logger::utils::applyAppender -appender $appenderType -serviceCmd $logger\
            -appenderArgs {-conversionPattern {\[%c\] \[%p\] '%m'}}
    ::logger::import -all -force -namespace log mecate

    variable version 1.2
}

<<mecate commands>>

package provide mecate $::mecate::version
----

................................................................................

=== Package Index

We also provide a root chunk to extract a package index file.

----
<<pkgIndex.tcl>>=
package ifneeded mecate 1.2 [list source [file join $dir mecate.tcl]]
----

=== Template

The following is a template that can be used to seed a unit test file
that uses `mecate`.








<
<







 







|







 







|







1766
1767
1768
1769
1770
1771
1772


1773
1774
1775
1776
1777
1778
1779
....
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
....
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
    } else {
        set insts $participants
    }

    set extlabel BOUNDARY ;        # <1>
    <<seqDiag: declare participants>>



    if {[dict get $seqDiagConfig -showstates]} {
        <<seqDiag: indicate initial state of each participant>>
    }

    set traces [pipe {
        rvajoin $traces [relvar set TransitionTrace] Transition |
        rvajoin ~ [relvar set PolymorphicTrace] Polymorphic |
................................................................................
    set logger [::logger::init mecate]
    set appenderType [expr {[dict exist [fconfigure stdout] -mode] ?\
            "colorConsole" : "console"}]
    ::logger::utils::applyAppender -appender $appenderType -serviceCmd $logger\
            -appenderArgs {-conversionPattern {\[%c\] \[%p\] '%m'}}
    ::logger::import -all -force -namespace log mecate

    variable version 1.2.1
}

<<mecate commands>>

package provide mecate $::mecate::version
----

................................................................................

=== Package Index

We also provide a root chunk to extract a package index file.

----
<<pkgIndex.tcl>>=
package ifneeded mecate 1.2.1 [list source [file join $dir mecate.tcl]]
----

=== Template

The following is a template that can be used to seed a unit test file
that uses `mecate`.

Added modules/mecate-1.2.1.tm.







































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
# DO NOT EDIT THIS FILE!
# THIS FILE IS AUTOMATICALLY GENERATED FROM A LITERATE PROGRAM SOURCE FILE.
#
# This software is copyrighted 2018 by G. Andrew Mangogna.
# The following terms apply to all files associated with the software unless
# explicitly disclaimed in individual files.
# 
# The authors hereby grant permission to use, copy, modify, distribute,
# and license this software and its documentation for any purpose, provided
# that existing copyright notices are retained in all copies and that this
# notice is included verbatim in any distributions. No written agreement,
# license, or royalty fee is required for any of the authorized uses.
# Modifications to this software may be copyrighted by their authors and
# need not follow the licensing terms described here, provided that the
# new terms are clearly indicated on the first page of each file where
# they apply.
# 
# IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
# DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING
# OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES
# THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
# 
# THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE
# IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE
# NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS,
# OR MODIFICATIONS.
# 
# GOVERNMENT USE: If you are acquiring this software on behalf of the
# U.S. government, the Government shall have only "Restricted Rights"
# in the software and related documentation as defined in the Federal
# Acquisition Regulations (FARs) in Clause 52.227.19 (c) (2).  If you
# are acquiring the software on behalf of the Department of Defense,
# the software shall be classified as "Commercial Computer Software"
# and the Government shall have only "Restricted Rights" as defined in
# Clause 252.227-7013 (c) (1) of DFARs.  Notwithstanding the foregoing,
# the authors grant the U.S. Government and others acting in its behalf
# permission to use and distribute the software in accordance with the
# terms specified in this license.
#

package require Tcl 8.6
package require logger
package require logger::utils
package require logger::appender
package require ral
package require ralutil
package require oo::util
package require struct::queue

namespace eval ::mecate {
    namespace export rein
    namespace export eventTraceFormat
    namespace export instrTraceFormat
    namespace export fatalTraceFormat
    namespace ensemble create

    set logger [::logger::init mecate]
    set appenderType [expr {[dict exist [fconfigure stdout] -mode] ?\
            "colorConsole" : "console"}]
    ::logger::utils::applyAppender -appender $appenderType -serviceCmd $logger\
            -appenderArgs {-conversionPattern {\[%c\] \[%p\] '%m'}}
    ::logger::import -all -force -namespace log mecate

    variable version 1.2.1
}

::oo::class create ::mecate::rein {
    constructor {args} {
        ::logger::import -all -namespace log mecate
    
        set timeout 2000
        foreach {option value} $args {
            switch -exact -- $option {
                -timeout {
                    set timeout $value
                }
                default {
                    my Throw "unknown option, \"$option\""
                }
            }
        }
    
        log::debug "-timeout option = \"$timeout\""
    
        my variable tracesReceived
        set tracesReceived [::struct::queue]
    
        my variable instrReceived
        set instrReceived [::struct::queue]
    
        my variable fatalReceived
        set fatalReceived [::struct::queue]
    
        my variable tracePrefix
        set tracePrefix {}
        my variable instrPrefix
        set instrPrefix {}
        my variable fatalPrefix
        set fatalPrefix {}
    
        my variable seqDiagConfig
        set seqDiagConfig [dict create\
            -showstates false\
            -participants {}\
        ]
    
        namespace import ::ral::*
        namespace import ::ralutil::*
    
        relvar create Trace {
            TraceId     int
            Time        string
            Event       string
            Source      string
            Target      string
        } TraceId
        
        relvar create TransitionTrace {
            TraceId     int
            Current     string
            New         string
        } TraceId
        
        relvar create PolymorphicTrace {
            TraceId         int
            Relationship    string
            NewEvent        string
            Subclass        string
        } TraceId
        
        relvar create CreationTrace {
            TraceId         int
        } TraceId
        
        relvar partition R1 Trace TraceId\
            TransitionTrace TraceId\
            PolymorphicTrace TraceId\
            CreationTrace TraceId
        relvar create Instrumentation {
            TraceId     int
            Time        string
            Message     string
        } TraceId
        relvar create Fatal {
            TraceId     int
            Time        string
            Message     string
        } TraceId
    
        return
    }
    variable timeout connection
    destructor {
        my disconnect
    
        my variable tracesReceived
        $tracesReceived destroy
    
        my variable instrReceived
        $instrReceived destroy
    
        my variable fatalReceived
        $fatalReceived destroy
    
        relvar constraint delete R1
        relvar unset Trace TransitionTrace PolymorphicTrace CreationTrace\
                Instrumentation Fatal
    }
    method cget {option} {
        switch -exact -- $option {
            -timeout {
                return [set [string range $option 1 end]]
            }
    
            default {
                my Throw "unknown option, \"$option\""
            }
        }
    }
    method configure {args} {
        foreach {option value} $args {
            switch -exact -- $option {
                -timeout {
                    set [string range $option 1 end] $value
                }
    
                default {
                    my Throw "unknown option, \"$option\""
                }
            }
        }
    
        return
    }
    method start {program {delay 500}} {
        log::info "starting harness program, \"$program\""
        set progargs [auto_execok $program]
        if {$progargs eq {}} {
            my Throw "unknown program, \"$program\""
        }
        set pid [exec -ignorestderr -- $progargs &]
        after $delay
        return $pid
    }
    method connect {{port 3906}} {
        log::info "connecting to localhost:$port"
    
        set tries 0                                                             ; # <1>
        while {true} {
            try {
                set connection [socket localhost $port]
                chan configure $connection -blocking true -buffering line
                chan event $connection readable [mymethod HandleHarnessInput]   ; # <2>
                return
            } on error {result opts} {
                incr tries
                if {$tries >= 3} {
                    log::error "connection failure after $tries attempts"
                    return -options $opts $result
                }
                log::notice "connection attempt failed, waiting 500 ms to try again"
                after 500
            }
        }
    }
    method disconnect {} {
        log::info "disconnecting from test harness"
        if {[info exists connection]} {
            catch {chan close $connection}
            unset -nocomplain connection
        }
        return
    }
    method null {} {
        return [my Command null]                ; # <1>
    }
    method version {} {
        return [my Command version]
    }
    method query {what args} {
        return [my Command query $what {*}$args]
    }
    method domainop {domain opname args} {
        return [my Command domainop $domain $opname {*}$args]
    }
    method create {domain class} {
        return [my Command create $domain $class]
    }
    method delete {domain class inst} {
        return [my Command delete $domain $class $inst]
    }
    method read {domain class inst args} {
        return [my Command read $domain $class $inst {*}$args]
    }
    method update {domain class inst args} {
        return [my Command update $domain $class $inst {*}$args]
    }
    method signal {domain class inst event args} {
        return [my Command signal $domain $class $inst $event {*}$args]
    }
    method delaysignal {domain class inst delay event args} {
        return [my Command delaysignal $domain $class $inst $delay $event {*}$args]
    }
    method cancel {domain class inst event} {
        return [my Command cancel $domain $class $inst $event]
    }
    method remaining {domain class inst event} {
        return [my Command remaining $domain $class $inst $event]
    }
    method createasync {domain class event args} {
        return [my Command createasync $domain $class $event {*}$args]
    }
    method eloop {args} {
        return [my Command eloop {*}$args]
    }
    method trace {args} {
        return [my Command trace {*}$args]
    }
    method waitForEventTrace {args} {
        my variable tracesReceived
        my variable traceSyncVar
    
        set expect $args
        while {true} {
            while {[$tracesReceived size] != 0} {
                set actual [$tracesReceived get]
    
                if {[my MatchTrace $actual $expect]} {
                    return $actual
                } else {
                    log::debug "discarding trace, \"$actual\":\
                            failed to match, \"$expect\""
                }
            }
    
            set resolvedVarName [my varname traceSyncVar]
            set timer [expr {$timeout > 0 ?\
                [after $timeout [list set $resolvedVarName TIMEOUT]] : {}}]
            vwait $resolvedVarName
    
            if {$traceSyncVar eq "TIMEOUT"} {
                my Throw "timed out on receiving event traces"
            } elseif {$traceSyncVar eq "FATAL"} {
                my Throw "fatal run-time error"
            } else {
                if {$timer ne {}} {
                    after cancel $timer
                }
            }
        }
    }
    method MatchTrace {trace pattern} {
        set matchCount 0
        dict for {key value} $pattern {
            if {[dict exists $trace $key] &&\
                    [string match $value [dict get $trace $key]]} {
                incr matchCount
            }
        }
    
        return [expr {$matchCount == [dict size $pattern] ? "true" : "false"}]
    }
    method clearEventTraceCache {} {
        my variable tracesReceived
        while {[$tracesReceived size] != 0} {
            $tracesReceived get
        }
        return
    }
    method formatEventTraces {{begin 1} {finish end}} {
        set traces [pipe {
            my RestrictTraces $begin $finish Trace |
            rvajoin ~ [relvar set TransitionTrace] Transition |
            rvajoin ~ [relvar set PolymorphicTrace] Polymorphic |
            rvajoin ~ [relvar set CreationTrace] Creation
        }]                                                      ; # <1>
    
        set listing [list]                                      ; # <2>
        relation foreach trace $traces -ascending TraceId {
            relation assign $trace
            set line {}
            append line [format "% 3u " $TraceId]
            if {[relation isnotempty $Transition]} {
                relation assign $Transition Current New
    
                append line [format\
                    "%s: Transition: %s - %s -> %s: %s ==> %s"\
                    $Time $Source $Event $Target $Current $New\
                ]
            } elseif {[relation isnotempty $Polymorphic]} {
                relation assign $Polymorphic Relationship NewEvent Subclass
    
                append line [format\
                    "%s: Polymorphic: %s - %s -> %s: %s - %s -> %s"\
                    $Time $Source $Event $Target $Relationship $NewEvent $Subclass\
                ]
            } elseif {[relation isnotempty $Creation]} {
                append line [format\
                    "%s: Creation: %s - %s -> %s"\
                    $Time $Source $Event $Target\
                ]
            }
    
            lappend listing $line
        }
    
        return [join $listing "\n"]
    }
    method RestrictTraces {begin finish which} {
        if {$begin == 1 && $finish eq "end"} {                  ; #  <1>
            set traces [relvar set $which]
        } else {
            if {$finish eq "end"} {
                set finish [relation cardinality [relvar set $which]]
            } elseif {![string is integer $finish]} {
                my Throw "bad finish value, \"$finish\""
            }
            set traces [relation restrictwith [relvar set $which]\
                    {$TraceId >= $begin && $TraceId <= $finish}]
        }
        return $traces
    }
    method discardEventTraces {} {
        variable traceId
        set traceId 0                   ; # <1>
        relvar eval {
            relvar set Trace [relation empty [relvar set Trace]]
            relvar set TransitionTrace [relation empty [relvar set TransitionTrace]]
            relvar set PolymorphicTrace [relation empty [relvar set PolymorphicTrace]]
            relvar set CreationTrace [relation empty [relvar set CreationTrace]]
        }                               ; # <2>
        return
    }
    method traceNotify {args} {
        my variable tracePrefix
        if {[llength $args] == 1} {
            set tracePrefix [lindex $args 0]
        } elseif {[llength $args] > 1} {
            my Throw "wrong number of arguments"
        }
        return $tracePrefix
    }
    method NotifyTraceArrived {trace} {
        my variable tracePrefix
        if {$tracePrefix eq {}} {
            return
        }
    
        try {
            eval [linsert $tracePrefix end $trace]
        } on error {result} {
            log::error "error notifying trace arrival: \"$result\""
            set tracePrefix {}                                          ; # <1>
        }
    }
    method seqDiag {{begin 1} {finish end}} {
        my variable seqDiagConfig
        lappend uml "@startuml"
        lappend uml "!pragma teoz true"
    
        set traces [my RestrictTraces $begin $finish Trace]
    
        set participants [dict get $seqDiagConfig -participants]
        if {[llength $participants] == 0} {
            set srcInsts [pipe {
                relation project $traces TraceId Source |
                relation rename ~ Source Name
            }] ;                                                                    # <1>
            set trgInsts [pipe {
                relation project $traces TraceId Target |
                relation rename ~ Target Name |
                relation update ~ t {1} {
                    tuple update $t TraceId [expr {[tuple extract $t TraceId] + 1}]}
            }] ;                                                                    # <2>
            set insts [pipe {
                relation union $srcInsts $trgInsts |
                relation summarizeby ~ Name s First int {rmin($s, "TraceId")} |
                relation list ~ Name -ascending First
            }] ;                                                                    # <3>
        } else {
            set insts $participants
        }
    
        set extlabel BOUNDARY ;        # <1>
        set bdindex [lsearch -exact $insts {?.?}]
        if {$bdindex != -1} {
            set insts [lreplace $insts $bdindex $bdindex $extlabel]
        }
        foreach inst $insts {
            set ptype [expr {$inst eq $extlabel ? "boundary" : "participant"}]
            lappend uml "$ptype \"$inst\""
        }
    
        if {[dict get $seqDiagConfig -showstates]} {
            set initialTransitions [pipe {
                relation join $traces [relvar set TransitionTrace] |
                relation summarizeby ~ Target s TraceId int {rmin($s, "TraceId")} |
                relation join ~ [relvar set TransitionTrace]
            }] ;                                                                      # <1>
            
            set initialStatePrefix {} ;
            relation foreach trans $initialTransitions {
                relation assign $trans
                if {$Target ni $insts} {
                    continue
                }
                if {$Current ne "@"} {
                    lappend uml "$initialStatePrefix rnote over \"$Target\" : $Current" ; # <2>
                    set initialStatePrefix & ;                                         # <3>
                }
            }
        }
    
        set traces [pipe {
            rvajoin $traces [relvar set TransitionTrace] Transition |
            rvajoin ~ [relvar set PolymorphicTrace] Polymorphic |
            rvajoin ~ [relvar set CreationTrace] Creation
        }]
    
        relation foreach trace $traces -ascending TraceId {
            relation assign $trace
    
            if {$Source eq "?.?"} {
                set Source $extlabel
            }
    
            if {!($Source in $insts && $Target in $insts)} {
                continue
            }
    
            if {[relation isnotempty $Transition]} {
                relation assign $Transition
                lappend uml "\"$Source\" --> \"$Target\" : $Event"
                if {[dict get $seqDiagConfig -showstates]} {
                    switch -exact -- $New {
                        CH {
                            lappend uml "hnote over \"$Target\" #red : Can't Happen!"
                        }
                        IG {
                            lappend uml "hnote over \"$Target\" #yellow : Ignored"
                        }
                        default {
                            lappend uml "rnote over \"$Target\" : $New"
                        }
                    }
                }
            } elseif {[relation isnotempty $Creation]} {
                lappend uml "create \"$Target\""
                lappend uml "\"$Source\" -> \"$Target\" : $Event <<create>>"
            } elseif {[relation isnotempty $Polymorphic]} {
                relation assign $Polymorphic
                lappend uml "\"$Source\" --> \"$Target\" :\
                        $Event <<poly \[$Relationship\]>>"
            }
        }
    
        lappend uml "@enduml"
    
        return [join $uml "\n"]
    }
    method seqDiagConfig {args} {
        if {[llength $args] % 2 != 0} {
            my Throw "options must be given as name / value pairs, got \"$args\""
        }
        my variable seqDiagConfig
    
        foreach {optname optvalue} $args {
            if {[dict exists $seqDiagConfig $optname]} {
                dict set seqDiagConfig $optname $optvalue
            } else {
                my Throw "unknown sequence diagram option, \"$optname\""
            }
        }
    
        return $seqDiagConfig
    }
    method seqDiagToChan {channel {begin 1} {finish end}} {
        chan puts $channel [my seqDiag $begin $finish]
        return
    }
    method seqDiagToFile {file {begin 1} {finish end}} {
        set channel [open $file w]
        try {
            my seqDiagToChan $channel $begin $finish
        } finally {
            chan close $channel
        }
        return
    }
    method instr {args} {
        return [my Command instr {*}$args]
    }
    method waitForInstrTrace {args} {
        my variable instrReceived
        my variable instrSyncVar
    
        set expect $args
        while {true} {
            while {[$instrReceived size] != 0} {
                set actual [$instrReceived get]
    
                if {[my MatchTrace $actual $expect]} {
                    return $actual
                } else {
                    log::debug "discarding trace, \"$actual\":\
                            failed to match, \"$expect\""
                }
            }
    
            set resolvedVarName [my varname instrSyncVar]
            set timer [expr {$timeout > 0 ?\
                [after $timeout [list set $resolvedVarName TIMEOUT]] : {}}]
            vwait $resolvedVarName
    
            if {$instrSyncVar eq "TIMEOUT"} {
                my Throw "timed out on receiving event traces"
            } elseif {$instrSyncVar eq "FATAL"} {
                my Throw "fatal run-time error"
            } else {
                if {$timer ne {}} {
                    after cancel $timer
                }
            }
        }
    }
    method clearInstrTraceCache {} {
        my variable instrReceived
        while {[$instrReceived size] != 0} {
            $instrReceived get
        }
    }
    method formatInstrTraces {{begin 1} {finish end}} {
        set listing [list]
        set instrs [my RestrictTraces $begin $finish Instrumentation]
    
        relation foreach instr $instrs -ascending TraceId {
            relation assign $instr
            lappend listing [format "% 3u %s: %s" $TraceId $Time $Message]
        }
    
        return [join $listing "\n"]
    }
    method discardInstrTraces {} {
        my variable instrId
        set instrId 0
        relvar eval {
            relvar set Instrumentation [relation empty [relvar set Instrumentation]]
        }
        return
    }
    method instrNotify {args} {
        my variable instrPrefix
        if {[llength $args] == 1} {
            set instrPrefix [lindex $args 0]
        } elseif {[llength $args] > 1} {
            my Throw "wrong number of arguments"
        }
        return $instrPrefix
    }
    method NotifyInstrArrived {instr} {
        my variable instrPrefix
        if {$instrPrefix eq {}} {
            return
        }
    
        try {
            eval [linsert $instrPrefix end $instr]
        } on error {result} {
            log::error "error notifying instrumentation arrival: \"$result\""
            set instrPrefix {}
        }
    }
    method waitForFatalTrace {args} {
        my variable fatalReceived
        my variable fatalSyncVar
    
        set expect $args
        while {true} {
            while {[$fatalReceived size] != 0} {
                set actual [$fatalReceived get]
    
                if {[my MatchTrace $actual $expect]} {
                    return $actual
                } else {
                    log::debug "discarding trace, \"$actual\":\
                            failed to match, \"$expect\""
                }
            }
    
            set resolvedVarName [my varname fatalSyncVar]
            set timer [expr {$timeout > 0 ?\
                [after $timeout [list set $resolvedVarName TIMEOUT]] : {}}]
            vwait $resolvedVarName
    
            if {$fatalSyncVar eq "TIMEOUT"} {
                my Throw "timed out on receiving event traces"
            } else {
                if {$timer ne {}} {
                    after cancel $timer
                }
            }
        }
    }
    method clearFatalTraceCache {} {
        my variable fatalReceived
        while {[$fatalReceived size] != 0} {
            $fatalReceived get
        }
    }
    method formatFatalTraces {{begin 1} {finish end}} {
        set listing [list]
        set fatals [my RestrictTraces $begin $finish Fatal]
    
        relation foreach fatal $fatals -ascending TraceId {
            relation assign $fatal
            lappend listing [format "% 3u %s: %s" $TraceId $Time $Message]
        }
    
        return [join $listing "\n"]
    }
    method discardFatalTraces {} {
        variable fatalId
        set fatalId 0
        relvar eval {
            relvar set Fatal [relation empty [relvar set Fatal]]
        }
        return
    }
    method fatalNotify {args} {
        my variable fatalPrefix
        if {[llength $args] == 1} {
            set fatalPrefix [lindex $args 0]
        } elseif {[llength $args] > 1} {
            my Throw "wrong number of arguments"
        }
        return $fatalPrefix
    }
    method NotifyFatalArrived {fatal} {
        my variable fatalPrefix
        if {$fatalPrefix eq {}} {
            return
        }
    
        try {
            eval [linsert $fatalPrefix end $fatal]
        } on error {result} {
            log::error "error notifying fatal error arrival: \"$result\""
            set fatalPrefix {}
        }
    }
    method saveTraces {file {how ral}} {
        switch -exact -- $how {
            ral {
                serializeToFile $file [self namespace]::*
            }
            sqlite {
                storeToSQLite $file [self namespace]::*
            }
            default {
                my Throw "unknown trace file type, \"$how\""
            }
        }
        return
    }
    method Puts {cmd} {
        log::debug "harness command: \"$cmd\""
        puts $connection $cmd
    }
    method HandleHarnessInput {} {
        set line {}
        for {set gotline false} {!$gotline} {set gotline [string is list $line]} {
            set llen [chan gets $connection input]
            if {$llen == -1} {
                if {[chan eof $connection]} {
                    log::warn "EOF on harness input -- closing \"$connection\""
                    chan close $connection
                    unset -nocomplain connection
                    return
                } elseif {[chan blocked $connection]} {
                    log::notice "partial line received"
                }
            } else {
                append line $input
            }
        }
        if {[string length $line] != 0} {
            log::debug "harness response: \"$line\""
        
            lassign $line resp_type resp_value
        
            switch -exact -- $resp_type {
                cmd {
                    my HandleCmdResponse $resp_value
                }
                trace {
                    my HandleTraceResponse $resp_value
                }
                fatal {
                    my HandleFatalResponse $resp_value
                }
                instr {
                    my HandleInstrResponse $resp_value
                }
                default {
                    my Throw "unknown response type, \"$resp_value\""
                }
            }
        }
    }
    method HandleCmdResponse {respValue} {
        set [my varname cmdSyncVar] $respValue
        return
    }
    method HandleTraceResponse {respValue} {
        my variable traceId
        incr traceId
    
        relvar eval {
            switch -exact -- [dict get $respValue type] {
                transition {
                    relvar insert TransitionTrace [list\
                        TraceId     $traceId\
                        Current     [dict get $respValue currstate]\
                        New         [dict get $respValue newstate]\
                    ]
                }
                polymorphic {
                    relvar insert PolymorphicTrace [list\
                        TraceId         $traceId\
                        Relationship    [dict get $respValue relationship]\
                        NewEvent        [dict get $respValue newevent]\
                        Subclass        [dict get $respValue subclass]\
                    ]
                }
                creation {
                    relvar insert CreationTrace [list\
                        TraceId     $traceId\
                    ]
                }
                default {
                    log::error "unknown state machine trace type,\
                            \"[dict get $respValue type]\""
                    incr traceId -1
                    return                                              ; # <1>
                }
            }
    
            relvar insert Trace [list\
                TraceId     $traceId\
                Time        [dict get $respValue time]\
                Event       [dict get $respValue event]\
                Source      [dict get $respValue source]\
                Target      [dict get $respValue target]\
            ]
        }
    
        my variable tracesReceived
        $tracesReceived put $respValue
        set [my varname traceSyncVar] TRACE
    
        my NotifyTraceArrived $respValue
    
        return
    }
    method HandleInstrResponse {respValue} {
        variable instrReceived
        $instrReceived put $respValue
    
        variable instrId
        incr instrId
        relvar insert Instrumentation [list\
            TraceId     $instrId\
            Time        [dict get $respValue time]\
            Message     [dict get $respValue message]\
        ]
    
        set [my varname instrSyncVar] INSTR
    
        my NotifyInstrArrived $respValue
    
        return
    }
    method HandleFatalResponse {respValue} {
        my variable fatalReceived
        $fatalReceived put $respValue
    
        variable fatalId
        incr fatalId
        relvar insert Fatal [list\
            TraceId     $fatalId\
            Time        [dict get $respValue time]\
            Message     [dict get $respValue message]\
        ]
    
        log::error "received fatal error response, \"$respValue\""
        set [my varname fatalSyncVar] FATAL
        set [my varname cmdSyncVar] FATAL
        set [my varname traceSyncVar] FATAL
    
        my NotifyFatalArrived $respValue
    
        return
    }
    method Command {args} {
        set resolvedVarName [my varname cmdSyncVar]
        set timer [expr {$timeout > 0 ?\
            [after $timeout [list set $resolvedVarName TIMEOUT]] : {}}]
    
        my Puts $args                                   ; # <1>
    
        vwait $resolvedVarName                          ; # <2>
    
        set cmdName [lindex $args 0]
        my variable cmdSyncVar
    
        if {$cmdSyncVar eq "TIMEOUT"} {
            my Throw "timeout for command, \"$cmdName\""
        } elseif {$cmdSyncVar eq "FATAL"} {
            my Throw "fatal run-time error while executing, \"$cmdName\""
        } else {
            if {$timer ne {}} {
                after cancel $timer
            }
        }
    
        if {[dict get $cmdSyncVar name] ne $cmdName} {
            my Throw "expected response for command,\
                    \"$cmdName\",\
                    got, \"[dict get $cmdSyncVar name]\""
        }
    
        set result [dict get $cmdSyncVar result]        ; # <3>
        if {[dict get $cmdSyncVar status] eq "error"} {
            my Throw $result
        }
    
        return $result
    }
    method Throw {message} {
        tailcall uplevel 1 [list throw [list {*}[self caller] $message] $message]
    }
}
proc ::mecate::eventTraceFormat {trace} {
    dict with trace {
        switch -exact -- $type {
            transition {
                return [format\
                    "%s: Transition: %s - %s -> %s: %s ==> %s"\
                    $time $source $event $target $currstate $newstate\
                ]
            }
            polymorphic {
                return [format\
                    "%s: Polymorphic: %s - %s -> %s: %s - %s -> %s"\
                    $time $source $event $target $relationship $newevent\
                    $subclass\
                ]
            }
            creation {
                return [format\
                    "%s: Creation: %s - %s -> %s"\
                    $time $source $event $target\
                ]
            }
            default {
                my Throw "unknown trace type, \"$type\""
            }
        }
    }
}
proc ::mecate::instrTraceFormat {trace} {
    dict with trace {
        return [format "%s: Instr: %s" $time $message]
    }
}
proc ::mecate::fatalTraceFormat {trace} {
    dict with trace {
        return [format "%s: Fatal: %s" $time $message]
    }
}

package provide mecate $::mecate::version



Deleted modules/mecate-1.2.tm.

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
# DO NOT EDIT THIS FILE!
# THIS FILE IS AUTOMATICALLY GENERATED FROM A LITERATE PROGRAM SOURCE FILE.
#
# This software is copyrighted 2018 by G. Andrew Mangogna.
# The following terms apply to all files associated with the software unless
# explicitly disclaimed in individual files.
# 
# The authors hereby grant permission to use, copy, modify, distribute,
# and license this software and its documentation for any purpose, provided
# that existing copyright notices are retained in all copies and that this
# notice is included verbatim in any distributions. No written agreement,
# license, or royalty fee is required for any of the authorized uses.
# Modifications to this software may be copyrighted by their authors and
# need not follow the licensing terms described here, provided that the
# new terms are clearly indicated on the first page of each file where
# they apply.
# 
# IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
# DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING
# OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES
# THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
# 
# THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE
# IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE
# NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS,
# OR MODIFICATIONS.
# 
# GOVERNMENT USE: If you are acquiring this software on behalf of the
# U.S. government, the Government shall have only "Restricted Rights"
# in the software and related documentation as defined in the Federal
# Acquisition Regulations (FARs) in Clause 52.227.19 (c) (2).  If you
# are acquiring the software on behalf of the Department of Defense,
# the software shall be classified as "Commercial Computer Software"
# and the Government shall have only "Restricted Rights" as defined in
# Clause 252.227-7013 (c) (1) of DFARs.  Notwithstanding the foregoing,
# the authors grant the U.S. Government and others acting in its behalf
# permission to use and distribute the software in accordance with the
# terms specified in this license.
#

package require Tcl 8.6
package require logger
package require logger::utils
package require logger::appender
package require ral
package require ralutil
package require oo::util
package require struct::queue

namespace eval ::mecate {
    namespace export rein
    namespace export eventTraceFormat
    namespace export instrTraceFormat
    namespace export fatalTraceFormat
    namespace ensemble create

    set logger [::logger::init mecate]
    set appenderType [expr {[dict exist [fconfigure stdout] -mode] ?\
            "colorConsole" : "console"}]
    ::logger::utils::applyAppender -appender $appenderType -serviceCmd $logger\
            -appenderArgs {-conversionPattern {\[%c\] \[%p\] '%m'}}
    ::logger::import -all -force -namespace log mecate

    variable version 1.2
}

::oo::class create ::mecate::rein {
    constructor {args} {
        ::logger::import -all -namespace log mecate
    
        set timeout 2000
        foreach {option value} $args {
            switch -exact -- $option {
                -timeout {
                    set timeout $value
                }
                default {
                    my Throw "unknown option, \"$option\""
                }
            }
        }
    
        log::debug "-timeout option = \"$timeout\""
    
        my variable tracesReceived
        set tracesReceived [::struct::queue]
    
        my variable instrReceived
        set instrReceived [::struct::queue]
    
        my variable fatalReceived
        set fatalReceived [::struct::queue]
    
        my variable tracePrefix
        set tracePrefix {}
        my variable instrPrefix
        set instrPrefix {}
        my variable fatalPrefix
        set fatalPrefix {}
    
        my variable seqDiagConfig
        set seqDiagConfig [dict create\
            -showstates false\
            -participants {}\
        ]
    
        namespace import ::ral::*
        namespace import ::ralutil::*
    
        relvar create Trace {
            TraceId     int
            Time        string
            Event       string
            Source      string
            Target      string
        } TraceId
        
        relvar create TransitionTrace {
            TraceId     int
            Current     string
            New         string
        } TraceId
        
        relvar create PolymorphicTrace {
            TraceId         int
            Relationship    string
            NewEvent        string
            Subclass        string
        } TraceId
        
        relvar create CreationTrace {
            TraceId         int
        } TraceId
        
        relvar partition R1 Trace TraceId\
            TransitionTrace TraceId\
            PolymorphicTrace TraceId\
            CreationTrace TraceId
        relvar create Instrumentation {
            TraceId     int
            Time        string
            Message     string
        } TraceId
        relvar create Fatal {
            TraceId     int
            Time        string
            Message     string
        } TraceId
    
        return
    }
    variable timeout connection
    destructor {
        my disconnect
    
        my variable tracesReceived
        $tracesReceived destroy
    
        my variable instrReceived
        $instrReceived destroy
    
        my variable fatalReceived
        $fatalReceived destroy
    
        relvar constraint delete R1
        relvar unset Trace TransitionTrace PolymorphicTrace CreationTrace\
                Instrumentation Fatal
    }
    method cget {option} {
        switch -exact -- $option {
            -timeout {
                return [set [string range $option 1 end]]
            }
    
            default {
                my Throw "unknown option, \"$option\""
            }
        }
    }
    method configure {args} {
        foreach {option value} $args {
            switch -exact -- $option {
                -timeout {
                    set [string range $option 1 end] $value
                }
    
                default {
                    my Throw "unknown option, \"$option\""
                }
            }
        }
    
        return
    }
    method start {program {delay 500}} {
        log::info "starting harness program, \"$program\""
        set progargs [auto_execok $program]
        if {$progargs eq {}} {
            my Throw "unknown program, \"$program\""
        }
        set pid [exec -ignorestderr -- $progargs &]
        after $delay
        return $pid
    }
    method connect {{port 3906}} {
        log::info "connecting to localhost:$port"
    
        set tries 0                                                             ; # <1>
        while {true} {
            try {
                set connection [socket localhost $port]
                chan configure $connection -blocking true -buffering line
                chan event $connection readable [mymethod HandleHarnessInput]   ; # <2>
                return
            } on error {result opts} {
                incr tries
                if {$tries >= 3} {
                    log::error "connection failure after $tries attempts"
                    return -options $opts $result
                }
                log::notice "connection attempt failed, waiting 500 ms to try again"
                after 500
            }
        }
    }
    method disconnect {} {
        log::info "disconnecting from test harness"
        if {[info exists connection]} {
            catch {chan close $connection}
            unset -nocomplain connection
        }
        return
    }
    method null {} {
        return [my Command null]                ; # <1>
    }
    method version {} {
        return [my Command version]
    }
    method query {what args} {
        return [my Command query $what {*}$args]
    }
    method domainop {domain opname args} {
        return [my Command domainop $domain $opname {*}$args]
    }
    method create {domain class} {
        return [my Command create $domain $class]
    }
    method delete {domain class inst} {
        return [my Command delete $domain $class $inst]
    }
    method read {domain class inst args} {
        return [my Command read $domain $class $inst {*}$args]
    }
    method update {domain class inst args} {
        return [my Command update $domain $class $inst {*}$args]
    }
    method signal {domain class inst event args} {
        return [my Command signal $domain $class $inst $event {*}$args]
    }
    method delaysignal {domain class inst delay event args} {
        return [my Command delaysignal $domain $class $inst $delay $event {*}$args]
    }
    method cancel {domain class inst event} {
        return [my Command cancel $domain $class $inst $event]
    }
    method remaining {domain class inst event} {
        return [my Command remaining $domain $class $inst $event]
    }
    method createasync {domain class event args} {
        return [my Command createasync $domain $class $event {*}$args]
    }
    method eloop {args} {
        return [my Command eloop {*}$args]
    }
    method trace {args} {
        return [my Command trace {*}$args]
    }
    method waitForEventTrace {args} {
        my variable tracesReceived
        my variable traceSyncVar
    
        set expect $args
        while {true} {
            while {[$tracesReceived size] != 0} {
                set actual [$tracesReceived get]
    
                if {[my MatchTrace $actual $expect]} {
                    return $actual
                } else {
                    log::debug "discarding trace, \"$actual\":\
                            failed to match, \"$expect\""
                }
            }
    
            set resolvedVarName [my varname traceSyncVar]
            set timer [expr {$timeout > 0 ?\
                [after $timeout [list set $resolvedVarName TIMEOUT]] : {}}]
            vwait $resolvedVarName
    
            if {$traceSyncVar eq "TIMEOUT"} {
                my Throw "timed out on receiving event traces"
            } elseif {$traceSyncVar eq "FATAL"} {
                my Throw "fatal run-time error"
            } else {
                if {$timer ne {}} {
                    after cancel $timer
                }
            }
        }
    }
    method MatchTrace {trace pattern} {
        set matchCount 0
        dict for {key value} $pattern {
            if {[dict exists $trace $key] &&\
                    [string match $value [dict get $trace $key]]} {
                incr matchCount
            }
        }
    
        return [expr {$matchCount == [dict size $pattern] ? "true" : "false"}]
    }
    method clearEventTraceCache {} {
        my variable tracesReceived
        while {[$tracesReceived size] != 0} {
            $tracesReceived get
        }
        return
    }
    method formatEventTraces {{begin 1} {finish end}} {
        set traces [pipe {
            my RestrictTraces $begin $finish Trace |
            rvajoin ~ [relvar set TransitionTrace] Transition |
            rvajoin ~ [relvar set PolymorphicTrace] Polymorphic |
            rvajoin ~ [relvar set CreationTrace] Creation
        }]                                                      ; # <1>
    
        set listing [list]                                      ; # <2>
        relation foreach trace $traces -ascending TraceId {
            relation assign $trace
            set line {}
            append line [format "% 3u " $TraceId]
            if {[relation isnotempty $Transition]} {
                relation assign $Transition Current New
    
                append line [format\
                    "%s: Transition: %s - %s -> %s: %s ==> %s"\
                    $Time $Source $Event $Target $Current $New\
                ]
            } elseif {[relation isnotempty $Polymorphic]} {
                relation assign $Polymorphic Relationship NewEvent Subclass
    
                append line [format\
                    "%s: Polymorphic: %s - %s -> %s: %s - %s -> %s"\
                    $Time $Source $Event $Target $Relationship $NewEvent $Subclass\
                ]
            } elseif {[relation isnotempty $Creation]} {
                append line [format\
                    "%s: Creation: %s - %s -> %s"\
                    $Time $Source $Event $Target\
                ]
            }
    
            lappend listing $line
        }
    
        return [join $listing "\n"]
    }
    method RestrictTraces {begin finish which} {
        if {$begin == 1 && $finish eq "end"} {                  ; #  <1>
            set traces [relvar set $which]
        } else {
            if {$finish eq "end"} {
                set finish [relation cardinality [relvar set $which]]
            } elseif {![string is integer $finish]} {
                my Throw "bad finish value, \"$finish\""
            }
            set traces [relation restrictwith [relvar set $which]\
                    {$TraceId >= $begin && $TraceId <= $finish}]
        }
        return $traces
    }
    method discardEventTraces {} {
        variable traceId
        set traceId 0                   ; # <1>
        relvar eval {
            relvar set Trace [relation empty [relvar set Trace]]
            relvar set TransitionTrace [relation empty [relvar set TransitionTrace]]
            relvar set PolymorphicTrace [relation empty [relvar set PolymorphicTrace]]
            relvar set CreationTrace [relation empty [relvar set CreationTrace]]
        }                               ; # <2>
        return
    }
    method traceNotify {args} {
        my variable tracePrefix
        if {[llength $args] == 1} {
            set tracePrefix [lindex $args 0]
        } elseif {[llength $args] > 1} {
            my Throw "wrong number of arguments"
        }
        return $tracePrefix
    }
    method NotifyTraceArrived {trace} {
        my variable tracePrefix
        if {$tracePrefix eq {}} {
            return
        }
    
        try {
            eval [linsert $tracePrefix end $trace]
        } on error {result} {
            log::error "error notifying trace arrival: \"$result\""
            set tracePrefix {}                                          ; # <1>
        }
    }
    method seqDiag {{begin 1} {finish end}} {
        my variable seqDiagConfig
        lappend uml "@startuml"
        lappend uml "!pragma teoz true"
    
        set traces [my RestrictTraces $begin $finish Trace]
    
        set participants [dict get $seqDiagConfig -participants]
        if {[llength $participants] == 0} {
            set srcInsts [pipe {
                relation project $traces TraceId Source |
                relation rename ~ Source Name
            }] ;                                                                    # <1>
            set trgInsts [pipe {
                relation project $traces TraceId Target |
                relation rename ~ Target Name |
                relation update ~ t {1} {
                    tuple update $t TraceId [expr {[tuple extract $t TraceId] + 1}]}
            }] ;                                                                    # <2>
            set insts [pipe {
                relation union $srcInsts $trgInsts |
                relation summarizeby ~ Name s First int {rmin($s, "TraceId")} |
                relation list ~ Name -ascending First
            }] ;                                                                    # <3>
        } else {
            set insts $participants
        }
    
        set extlabel BOUNDARY ;        # <1>
        set bdindex [lsearch -exact $insts {?.?}]
        if {$bdindex != -1} {
            set insts [lreplace $insts $bdindex $bdindex $extlabel]
        }
        foreach inst $insts {
            set ptype [expr {$inst eq $extlabel ? "boundary" : "participant"}]
            lappend uml "$ptype \"$inst\""
        }
    
        puts "insts = [list $insts]"
    
        if {[dict get $seqDiagConfig -showstates]} {
            set initialTransitions [pipe {
                relation join $traces [relvar set TransitionTrace] |
                relation summarizeby ~ Target s TraceId int {rmin($s, "TraceId")} |
                relation join ~ [relvar set TransitionTrace]
            }] ;                                                                      # <1>
            
            set initialStatePrefix {} ;
            relation foreach trans $initialTransitions {
                relation assign $trans
                if {$Target ni $insts} {
                    continue
                }
                if {$Current ne "@"} {
                    lappend uml "$initialStatePrefix rnote over \"$Target\" : $Current" ; # <2>
                    set initialStatePrefix & ;                                         # <3>
                }
            }
        }
    
        set traces [pipe {
            rvajoin $traces [relvar set TransitionTrace] Transition |
            rvajoin ~ [relvar set PolymorphicTrace] Polymorphic |
            rvajoin ~ [relvar set CreationTrace] Creation
        }]
    
        relation foreach trace $traces -ascending TraceId {
            relation assign $trace
    
            if {$Source eq "?.?"} {
                set Source $extlabel
            }
    
            if {!($Source in $insts && $Target in $insts)} {
                continue
            }
    
            if {[relation isnotempty $Transition]} {
                relation assign $Transition
                lappend uml "\"$Source\" --> \"$Target\" : $Event"
                if {[dict get $seqDiagConfig -showstates]} {
                    switch -exact -- $New {
                        CH {
                            lappend uml "hnote over \"$Target\" #red : Can't Happen!"
                        }
                        IG {
                            lappend uml "hnote over \"$Target\" #yellow : Ignored"
                        }
                        default {
                            lappend uml "rnote over \"$Target\" : $New"
                        }
                    }
                }
            } elseif {[relation isnotempty $Creation]} {
                lappend uml "create \"$Target\""
                lappend uml "\"$Source\" -> \"$Target\" : $Event <<create>>"
            } elseif {[relation isnotempty $Polymorphic]} {
                relation assign $Polymorphic
                lappend uml "\"$Source\" --> \"$Target\" :\
                        $Event <<poly \[$Relationship\]>>"
            }
        }
    
        lappend uml "@enduml"
    
        return [join $uml "\n"]
    }
    method seqDiagConfig {args} {
        if {[llength $args] % 2 != 0} {
            my Throw "options must be given as name / value pairs, got \"$args\""
        }
        my variable seqDiagConfig
    
        foreach {optname optvalue} $args {
            if {[dict exists $seqDiagConfig $optname]} {
                dict set seqDiagConfig $optname $optvalue
            } else {
                my Throw "unknown sequence diagram option, \"$optname\""
            }
        }
    
        return $seqDiagConfig
    }
    method seqDiagToChan {channel {begin 1} {finish end}} {
        chan puts $channel [my seqDiag $begin $finish]
        return
    }
    method seqDiagToFile {file {begin 1} {finish end}} {
        set channel [open $file w]
        try {
            my seqDiagToChan $channel $begin $finish
        } finally {
            chan close $channel
        }
        return
    }
    method instr {args} {
        return [my Command instr {*}$args]
    }
    method waitForInstrTrace {args} {
        my variable instrReceived
        my variable instrSyncVar
    
        set expect $args
        while {true} {
            while {[$instrReceived size] != 0} {
                set actual [$instrReceived get]
    
                if {[my MatchTrace $actual $expect]} {
                    return $actual
                } else {
                    log::debug "discarding trace, \"$actual\":\
                            failed to match, \"$expect\""
                }
            }
    
            set resolvedVarName [my varname instrSyncVar]
            set timer [expr {$timeout > 0 ?\
                [after $timeout [list set $resolvedVarName TIMEOUT]] : {}}]
            vwait $resolvedVarName
    
            if {$instrSyncVar eq "TIMEOUT"} {
                my Throw "timed out on receiving event traces"
            } elseif {$instrSyncVar eq "FATAL"} {
                my Throw "fatal run-time error"
            } else {
                if {$timer ne {}} {
                    after cancel $timer
                }
            }
        }
    }
    method clearInstrTraceCache {} {
        my variable instrReceived
        while {[$instrReceived size] != 0} {
            $instrReceived get
        }
    }
    method formatInstrTraces {{begin 1} {finish end}} {
        set listing [list]
        set instrs [my RestrictTraces $begin $finish Instrumentation]
    
        relation foreach instr $instrs -ascending TraceId {
            relation assign $instr
            lappend listing [format "% 3u %s: %s" $TraceId $Time $Message]
        }
    
        return [join $listing "\n"]
    }
    method discardInstrTraces {} {
        my variable instrId
        set instrId 0
        relvar eval {
            relvar set Instrumentation [relation empty [relvar set Instrumentation]]
        }
        return
    }
    method instrNotify {args} {
        my variable instrPrefix
        if {[llength $args] == 1} {
            set instrPrefix [lindex $args 0]
        } elseif {[llength $args] > 1} {
            my Throw "wrong number of arguments"
        }
        return $instrPrefix
    }
    method NotifyInstrArrived {instr} {
        my variable instrPrefix
        if {$instrPrefix eq {}} {
            return
        }
    
        try {
            eval [linsert $instrPrefix end $instr]
        } on error {result} {
            log::error "error notifying instrumentation arrival: \"$result\""
            set instrPrefix {}
        }
    }
    method waitForFatalTrace {args} {
        my variable fatalReceived
        my variable fatalSyncVar
    
        set expect $args
        while {true} {
            while {[$fatalReceived size] != 0} {
                set actual [$fatalReceived get]
    
                if {[my MatchTrace $actual $expect]} {
                    return $actual
                } else {
                    log::debug "discarding trace, \"$actual\":\
                            failed to match, \"$expect\""
                }
            }
    
            set resolvedVarName [my varname fatalSyncVar]
            set timer [expr {$timeout > 0 ?\
                [after $timeout [list set $resolvedVarName TIMEOUT]] : {}}]
            vwait $resolvedVarName
    
            if {$fatalSyncVar eq "TIMEOUT"} {
                my Throw "timed out on receiving event traces"
            } else {
                if {$timer ne {}} {
                    after cancel $timer
                }
            }
        }
    }
    method clearFatalTraceCache {} {
        my variable fatalReceived
        while {[$fatalReceived size] != 0} {
            $fatalReceived get
        }
    }
    method formatFatalTraces {{begin 1} {finish end}} {
        set listing [list]
        set fatals [my RestrictTraces $begin $finish Fatal]
    
        relation foreach fatal $fatals -ascending TraceId {
            relation assign $fatal
            lappend listing [format "% 3u %s: %s" $TraceId $Time $Message]
        }
    
        return [join $listing "\n"]
    }
    method discardFatalTraces {} {
        variable fatalId
        set fatalId 0
        relvar eval {
            relvar set Fatal [relation empty [relvar set Fatal]]
        }
        return
    }
    method fatalNotify {args} {
        my variable fatalPrefix
        if {[llength $args] == 1} {
            set fatalPrefix [lindex $args 0]
        } elseif {[llength $args] > 1} {
            my Throw "wrong number of arguments"
        }
        return $fatalPrefix
    }
    method NotifyFatalArrived {fatal} {
        my variable fatalPrefix
        if {$fatalPrefix eq {}} {
            return
        }
    
        try {
            eval [linsert $fatalPrefix end $fatal]
        } on error {result} {
            log::error "error notifying fatal error arrival: \"$result\""
            set fatalPrefix {}
        }
    }
    method saveTraces {file {how ral}} {
        switch -exact -- $how {
            ral {
                serializeToFile $file [self namespace]::*
            }
            sqlite {
                storeToSQLite $file [self namespace]::*
            }
            default {
                my Throw "unknown trace file type, \"$how\""
            }
        }
        return
    }
    method Puts {cmd} {
        log::debug "harness command: \"$cmd\""
        puts $connection $cmd
    }
    method HandleHarnessInput {} {
        set line {}
        for {set gotline false} {!$gotline} {set gotline [string is list $line]} {
            set llen [chan gets $connection input]
            if {$llen == -1} {
                if {[chan eof $connection]} {
                    log::warn "EOF on harness input -- closing \"$connection\""
                    chan close $connection
                    unset -nocomplain connection
                    return
                } elseif {[chan blocked $connection]} {
                    log::notice "partial line received"
                }
            } else {
                append line $input
            }
        }
        if {[string length $line] != 0} {
            log::debug "harness response: \"$line\""
        
            lassign $line resp_type resp_value
        
            switch -exact -- $resp_type {
                cmd {
                    my HandleCmdResponse $resp_value
                }
                trace {
                    my HandleTraceResponse $resp_value
                }
                fatal {
                    my HandleFatalResponse $resp_value
                }
                instr {
                    my HandleInstrResponse $resp_value
                }
                default {
                    my Throw "unknown response type, \"$resp_value\""
                }
            }
        }
    }
    method HandleCmdResponse {respValue} {
        set [my varname cmdSyncVar] $respValue
        return
    }
    method HandleTraceResponse {respValue} {
        my variable traceId
        incr traceId
    
        relvar eval {
            switch -exact -- [dict get $respValue type] {
                transition {
                    relvar insert TransitionTrace [list\
                        TraceId     $traceId\
                        Current     [dict get $respValue currstate]\
                        New         [dict get $respValue newstate]\
                    ]
                }
                polymorphic {
                    relvar insert PolymorphicTrace [list\
                        TraceId         $traceId\
                        Relationship    [dict get $respValue relationship]\
                        NewEvent        [dict get $respValue newevent]\
                        Subclass        [dict get $respValue subclass]\
                    ]
                }
                creation {
                    relvar insert CreationTrace [list\
                        TraceId     $traceId\
                    ]
                }
                default {
                    log::error "unknown state machine trace type,\
                            \"[dict get $respValue type]\""
                    incr traceId -1
                    return                                              ; # <1>
                }
            }
    
            relvar insert Trace [list\
                TraceId     $traceId\
                Time        [dict get $respValue time]\
                Event       [dict get $respValue event]\
                Source      [dict get $respValue source]\
                Target      [dict get $respValue target]\
            ]
        }
    
        my variable tracesReceived
        $tracesReceived put $respValue
        set [my varname traceSyncVar] TRACE
    
        my NotifyTraceArrived $respValue
    
        return
    }
    method HandleInstrResponse {respValue} {
        variable instrReceived
        $instrReceived put $respValue
    
        variable instrId
        incr instrId
        relvar insert Instrumentation [list\
            TraceId     $instrId\
            Time        [dict get $respValue time]\
            Message     [dict get $respValue message]\
        ]
    
        set [my varname instrSyncVar] INSTR
    
        my NotifyInstrArrived $respValue
    
        return
    }
    method HandleFatalResponse {respValue} {
        my variable fatalReceived
        $fatalReceived put $respValue
    
        variable fatalId
        incr fatalId
        relvar insert Fatal [list\
            TraceId     $fatalId\
            Time        [dict get $respValue time]\
            Message     [dict get $respValue message]\
        ]
    
        log::error "received fatal error response, \"$respValue\""
        set [my varname fatalSyncVar] FATAL
        set [my varname cmdSyncVar] FATAL
        set [my varname traceSyncVar] FATAL
    
        my NotifyFatalArrived $respValue
    
        return
    }
    method Command {args} {
        set resolvedVarName [my varname cmdSyncVar]
        set timer [expr {$timeout > 0 ?\
            [after $timeout [list set $resolvedVarName TIMEOUT]] : {}}]
    
        my Puts $args                                   ; # <1>
    
        vwait $resolvedVarName                          ; # <2>
    
        set cmdName [lindex $args 0]
        my variable cmdSyncVar
    
        if {$cmdSyncVar eq "TIMEOUT"} {
            my Throw "timeout for command, \"$cmdName\""
        } elseif {$cmdSyncVar eq "FATAL"} {
            my Throw "fatal run-time error while executing, \"$cmdName\""
        } else {
            if {$timer ne {}} {
                after cancel $timer
            }
        }
    
        if {[dict get $cmdSyncVar name] ne $cmdName} {
            my Throw "expected response for command,\
                    \"$cmdName\",\
                    got, \"[dict get $cmdSyncVar name]\""
        }
    
        set result [dict get $cmdSyncVar result]        ; # <3>
        if {[dict get $cmdSyncVar status] eq "error"} {
            my Throw $result
        }
    
        return $result
    }
    method Throw {message} {
        tailcall uplevel 1 [list throw [list {*}[self caller] $message] $message]
    }
}
proc ::mecate::eventTraceFormat {trace} {
    dict with trace {
        switch -exact -- $type {
            transition {
                return [format\
                    "%s: Transition: %s - %s -> %s: %s ==> %s"\
                    $time $source $event $target $currstate $newstate\
                ]
            }
            polymorphic {
                return [format\
                    "%s: Polymorphic: %s - %s -> %s: %s - %s -> %s"\
                    $time $source $event $target $relationship $newevent\
                    $subclass\
                ]
            }
            creation {
                return [format\
                    "%s: Creation: %s - %s -> %s"\
                    $time $source $event $target\
                ]
            }
            default {
                my Throw "unknown trace type, \"$type\""
            }
        }
    }
}
proc ::mecate::instrTraceFormat {trace} {
    dict with trace {
        return [format "%s: Instr: %s" $time $message]
    }
}
proc ::mecate::fatalTraceFormat {trace} {
    dict with trace {
        return [format "%s: Fatal: %s" $time $message]
    }
}

package provide mecate $::mecate::version


<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<










































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted packages/package-mecate-1.2-tcl.tm.

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
# ACTIVESTATE TEAPOT-PKG BEGIN TM -*- tcl -*-
# -- Tcl Module

# @@ Meta Begin
# Package mecate 1.2
# Meta description Mecate is a package that provides a set of command to
# Meta description interact with bosal generated test harnesses.
# Meta platform    tcl
# Meta require     {Tcl 8.6}
# Meta require     logger
# Meta require     oo::util
# Meta require     ral
# Meta require     ralutil
# Meta require     struct::queue
# Meta summary     Command interface to bosal generated test harnesses.
# @@ Meta End


# ACTIVESTATE TEAPOT-PKG BEGIN REQUIREMENTS

package require Tcl 8.6
package require logger
package require oo::util
package require ral
package require ralutil
package require struct::queue

# ACTIVESTATE TEAPOT-PKG END REQUIREMENTS

# ACTIVESTATE TEAPOT-PKG BEGIN DECLARE

package provide mecate 1.2

# ACTIVESTATE TEAPOT-PKG END DECLARE
# ACTIVESTATE TEAPOT-PKG END TM
# DO NOT EDIT THIS FILE!
# THIS FILE IS AUTOMATICALLY GENERATED FROM A LITERATE PROGRAM SOURCE FILE.
#
# This software is copyrighted 2018 by G. Andrew Mangogna.
# The following terms apply to all files associated with the software unless
# explicitly disclaimed in individual files.
# 
# The authors hereby grant permission to use, copy, modify, distribute,
# and license this software and its documentation for any purpose, provided
# that existing copyright notices are retained in all copies and that this
# notice is included verbatim in any distributions. No written agreement,
# license, or royalty fee is required for any of the authorized uses.
# Modifications to this software may be copyrighted by their authors and
# need not follow the licensing terms described here, provided that the
# new terms are clearly indicated on the first page of each file where
# they apply.
# 
# IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
# DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING
# OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES
# THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
# 
# THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE
# IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE
# NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS,
# OR MODIFICATIONS.
# 
# GOVERNMENT USE: If you are acquiring this software on behalf of the
# U.S. government, the Government shall have only "Restricted Rights"
# in the software and related documentation as defined in the Federal
# Acquisition Regulations (FARs) in Clause 52.227.19 (c) (2).  If you
# are acquiring the software on behalf of the Department of Defense,
# the software shall be classified as "Commercial Computer Software"
# and the Government shall have only "Restricted Rights" as defined in
# Clause 252.227-7013 (c) (1) of DFARs.  Notwithstanding the foregoing,
# the authors grant the U.S. Government and others acting in its behalf
# permission to use and distribute the software in accordance with the
# terms specified in this license.
#

package require Tcl 8.6
package require logger
package require logger::utils
package require logger::appender
package require ral
package require ralutil
package require oo::util
package require struct::queue

namespace eval ::mecate {
    namespace export rein
    namespace export eventTraceFormat
    namespace export instrTraceFormat
    namespace export fatalTraceFormat
    namespace ensemble create

    set logger [::logger::init mecate]
    set appenderType [expr {[dict exist [fconfigure stdout] -mode] ?\
            "colorConsole" : "console"}]
    ::logger::utils::applyAppender -appender $appenderType -serviceCmd $logger\
            -appenderArgs {-conversionPattern {\[%c\] \[%p\] '%m'}}
    ::logger::import -all -force -namespace log mecate

    variable version 1.2
}

::oo::class create ::mecate::rein {
    constructor {args} {
        ::logger::import -all -namespace log mecate
    
        set timeout 2000
        foreach {option value} $args {
            switch -exact -- $option {
                -timeout {
                    set timeout $value
                }
                default {
                    my Throw "unknown option, \"$option\""
                }
            }
        }
    
        log::debug "-timeout option = \"$timeout\""
    
        my variable tracesReceived
        set tracesReceived [::struct::queue]
    
        my variable instrReceived
        set instrReceived [::struct::queue]
    
        my variable fatalReceived
        set fatalReceived [::struct::queue]
    
        my variable tracePrefix
        set tracePrefix {}
        my variable instrPrefix
        set instrPrefix {}
        my variable fatalPrefix
        set fatalPrefix {}
    
        my variable seqDiagConfig
        set seqDiagConfig [dict create\
            -showstates false\
            -participants {}\
        ]
    
        namespace import ::ral::*
        namespace import ::ralutil::*
    
        relvar create Trace {
            TraceId     int
            Time        string
            Event       string
            Source      string
            Target      string
        } TraceId
        
        relvar create TransitionTrace {
            TraceId     int
            Current     string
            New         string
        } TraceId
        
        relvar create PolymorphicTrace {
            TraceId         int
            Relationship    string
            NewEvent        string
            Subclass        string
        } TraceId
        
        relvar create CreationTrace {
            TraceId         int
        } TraceId
        
        relvar partition R1 Trace TraceId\
            TransitionTrace TraceId\
            PolymorphicTrace TraceId\
            CreationTrace TraceId
        relvar create Instrumentation {
            TraceId     int
            Time        string
            Message     string
        } TraceId
        relvar create Fatal {
            TraceId     int
            Time        string
            Message     string
        } TraceId
    
        return
    }
    variable timeout connection
    destructor {
        my disconnect
    
        my variable tracesReceived
        $tracesReceived destroy
    
        my variable instrReceived
        $instrReceived destroy
    
        my variable fatalReceived
        $fatalReceived destroy
    
        relvar constraint delete R1
        relvar unset Trace TransitionTrace PolymorphicTrace CreationTrace\
                Instrumentation Fatal
    }
    method cget {option} {
        switch -exact -- $option {
            -timeout {
                return [set [string range $option 1 end]]
            }
    
            default {
                my Throw "unknown option, \"$option\""
            }
        }
    }
    method configure {args} {
        foreach {option value} $args {
            switch -exact -- $option {
                -timeout {
                    set [string range $option 1 end] $value
                }
    
                default {
                    my Throw "unknown option, \"$option\""
                }
            }
        }
    
        return
    }
    method start {program {delay 500}} {
        log::info "starting harness program, \"$program\""
        set progargs [auto_execok $program]
        if {$progargs eq {}} {
            my Throw "unknown program, \"$program\""
        }
        set pid [exec -ignorestderr -- $progargs &]
        after $delay
        return $pid
    }
    method connect {{port 3906}} {
        log::info "connecting to localhost:$port"
    
        set tries 0                                                             ; # <1>
        while {true} {
            try {
                set connection [socket localhost $port]
                chan configure $connection -blocking true -buffering line
                chan event $connection readable [mymethod HandleHarnessInput]   ; # <2>
                return
            } on error {result opts} {
                incr tries
                if {$tries >= 3} {
                    log::error "connection failure after $tries attempts"
                    return -options $opts $result
                }
                log::notice "connection attempt failed, waiting 500 ms to try again"
                after 500
            }
        }
    }
    method disconnect {} {
        log::info "disconnecting from test harness"
        if {[info exists connection]} {
            catch {chan close $connection}
            unset -nocomplain connection
        }
        return
    }
    method null {} {
        return [my Command null]                ; # <1>
    }
    method version {} {
        return [my Command version]
    }
    method query {what args} {
        return [my Command query $what {*}$args]
    }
    method domainop {domain opname args} {
        return [my Command domainop $domain $opname {*}$args]
    }
    method create {domain class} {
        return [my Command create $domain $class]
    }
    method delete {domain class inst} {
        return [my Command delete $domain $class $inst]
    }
    method read {domain class inst args} {
        return [my Command read $domain $class $inst {*}$args]
    }
    method update {domain class inst args} {
        return [my Command update $domain $class $inst {*}$args]
    }
    method signal {domain class inst event args} {
        return [my Command signal $domain $class $inst $event {*}$args]
    }
    method delaysignal {domain class inst delay event args} {
        return [my Command delaysignal $domain $class $inst $delay $event {*}$args]
    }
    method cancel {domain class inst event} {
        return [my Command cancel $domain $class $inst $event]
    }
    method remaining {domain class inst event} {
        return [my Command remaining $domain $class $inst $event]
    }
    method createasync {domain class event args} {
        return [my Command createasync $domain $class $event {*}$args]
    }
    method eloop {args} {
        return [my Command eloop {*}$args]
    }
    method trace {args} {
        return [my Command trace {*}$args]
    }
    method waitForEventTrace {args} {
        my variable tracesReceived
        my variable traceSyncVar
    
        set expect $args
        while {true} {
            while {[$tracesReceived size] != 0} {
                set actual [$tracesReceived get]
    
                if {[my MatchTrace $actual $expect]} {
                    return $actual
                } else {
                    log::debug "discarding trace, \"$actual\":\
                            failed to match, \"$expect\""
                }
            }
    
            set resolvedVarName [my varname traceSyncVar]
            set timer [expr {$timeout > 0 ?\
                [after $timeout [list set $resolvedVarName TIMEOUT]] : {}}]
            vwait $resolvedVarName
    
            if {$traceSyncVar eq "TIMEOUT"} {
                my Throw "timed out on receiving event traces"
            } elseif {$traceSyncVar eq "FATAL"} {
                my Throw "fatal run-time error"
            } else {
                if {$timer ne {}} {
                    after cancel $timer
                }
            }
        }
    }
    method MatchTrace {trace pattern} {
        set matchCount 0
        dict for {key value} $pattern {
            if {[dict exists $trace $key] &&\
                    [string match $value [dict get $trace $key]]} {
                incr matchCount
            }
        }
    
        return [expr {$matchCount == [dict size $pattern] ? "true" : "false"}]
    }
    method clearEventTraceCache {} {
        my variable tracesReceived
        while {[$tracesReceived size] != 0} {
            $tracesReceived get
        }
        return
    }
    method formatEventTraces {{begin 1} {finish end}} {
        set traces [pipe {
            my RestrictTraces $begin $finish Trace |
            rvajoin ~ [relvar set TransitionTrace] Transition |
            rvajoin ~ [relvar set PolymorphicTrace] Polymorphic |
            rvajoin ~ [relvar set CreationTrace] Creation
        }]                                                      ; # <1>
    
        set listing [list]                                      ; # <2>
        relation foreach trace $traces -ascending TraceId {
            relation assign $trace
            set line {}
            append line [format "% 3u " $TraceId]
            if {[relation isnotempty $Transition]} {
                relation assign $Transition Current New
    
                append line [format\
                    "%s: Transition: %s - %s -> %s: %s ==> %s"\
                    $Time $Source $Event $Target $Current $New\
                ]
            } elseif {[relation isnotempty $Polymorphic]} {
                relation assign $Polymorphic Relationship NewEvent Subclass
    
                append line [format\
                    "%s: Polymorphic: %s - %s -> %s: %s - %s -> %s"\
                    $Time $Source $Event $Target $Relationship $NewEvent $Subclass\
                ]
            } elseif {[relation isnotempty $Creation]} {
                append line [format\
                    "%s: Creation: %s - %s -> %s"\
                    $Time $Source $Event $Target\
                ]
            }
    
            lappend listing $line
        }
    
        return [join $listing "\n"]
    }
    method RestrictTraces {begin finish which} {
        if {$begin == 1 && $finish eq "end"} {                  ; #  <1>
            set traces [relvar set $which]
        } else {
            if {$finish eq "end"} {
                set finish [relation cardinality [relvar set $which]]
            } elseif {![string is integer $finish]} {
                my Throw "bad finish value, \"$finish\""
            }
            set traces [relation restrictwith [relvar set $which]\
                    {$TraceId >= $begin && $TraceId <= $finish}]
        }
        return $traces
    }
    method discardEventTraces {} {
        variable traceId
        set traceId 0                   ; # <1>
        relvar eval {
            relvar set Trace [relation empty [relvar set Trace]]
            relvar set TransitionTrace [relation empty [relvar set TransitionTrace]]
            relvar set PolymorphicTrace [relation empty [relvar set PolymorphicTrace]]
            relvar set CreationTrace [relation empty [relvar set CreationTrace]]
        }                               ; # <2>
        return
    }
    method traceNotify {args} {
        my variable tracePrefix
        if {[llength $args] == 1} {
            set tracePrefix [lindex $args 0]
        } elseif {[llength $args] > 1} {
            my Throw "wrong number of arguments"
        }
        return $tracePrefix
    }
    method NotifyTraceArrived {trace} {
        my variable tracePrefix
        if {$tracePrefix eq {}} {
            return
        }
    
        try {
            eval [linsert $tracePrefix end $trace]
        } on error {result} {
            log::error "error notifying trace arrival: \"$result\""
            set tracePrefix {}                                          ; # <1>
        }
    }
    method seqDiag {{begin 1} {finish end}} {
        my variable seqDiagConfig
        lappend uml "@startuml"
        lappend uml "!pragma teoz true"
    
        set traces [my RestrictTraces $begin $finish Trace]
    
        set participants [dict get $seqDiagConfig -participants]
        if {[llength $participants] == 0} {
            set srcInsts [pipe {
                relation project $traces TraceId Source |
                relation rename ~ Source Name
            }] ;                                                                    # <1>
            set trgInsts [pipe {
                relation project $traces TraceId Target |
                relation rename ~ Target Name |
                relation update ~ t {1} {
                    tuple update $t TraceId [expr {[tuple extract $t TraceId] + 1}]}
            }] ;                                                                    # <2>
            set insts [pipe {
                relation union $srcInsts $trgInsts |
                relation summarizeby ~ Name s First int {rmin($s, "TraceId")} |
                relation list ~ Name -ascending First
            }] ;                                                                    # <3>
        } else {
            set insts $participants
        }
    
        set extlabel BOUNDARY ;        # <1>
        set bdindex [lsearch -exact $insts {?.?}]
        if {$bdindex != -1} {
            set insts [lreplace $insts $bdindex $bdindex $extlabel]
        }
        foreach inst $insts {
            set ptype [expr {$inst eq $extlabel ? "boundary" : "participant"}]
            lappend uml "$ptype \"$inst\""
        }
    
        puts "insts = [list $insts]"
    
        if {[dict get $seqDiagConfig -showstates]} {
            set initialTransitions [pipe {
                relation join $traces [relvar set TransitionTrace] |
                relation summarizeby ~ Target s TraceId int {rmin($s, "TraceId")} |
                relation join ~ [relvar set TransitionTrace]
            }] ;                                                                      # <1>
            
            set initialStatePrefix {} ;
            relation foreach trans $initialTransitions {
                relation assign $trans
                if {$Target ni $insts} {
                    continue
                }
                if {$Current ne "@"} {
                    lappend uml "$initialStatePrefix rnote over \"$Target\" : $Current" ; # <2>
                    set initialStatePrefix & ;                                         # <3>
                }
            }
        }
    
        set traces [pipe {
            rvajoin $traces [relvar set TransitionTrace] Transition |
            rvajoin ~ [relvar set PolymorphicTrace] Polymorphic |
            rvajoin ~ [relvar set CreationTrace] Creation
        }]
    
        relation foreach trace $traces -ascending TraceId {
            relation assign $trace
    
            if {$Source eq "?.?"} {
                set Source $extlabel
            }
    
            if {!($Source in $insts && $Target in $insts)} {
                continue
            }
    
            if {[relation isnotempty $Transition]} {
                relation assign $Transition
                lappend uml "\"$Source\" --> \"$Target\" : $Event"
                if {[dict get $seqDiagConfig -showstates]} {
                    switch -exact -- $New {
                        CH {
                            lappend uml "hnote over \"$Target\" #red : Can't Happen!"
                        }
                        IG {
                            lappend uml "hnote over \"$Target\" #yellow : Ignored"
                        }
                        default {
                            lappend uml "rnote over \"$Target\" : $New"
                        }
                    }
                }
            } elseif {[relation isnotempty $Creation]} {
                lappend uml "create \"$Target\""
                lappend uml "\"$Source\" -> \"$Target\" : $Event <<create>>"
            } elseif {[relation isnotempty $Polymorphic]} {
                relation assign $Polymorphic
                lappend uml "\"$Source\" --> \"$Target\" :\
                        $Event <<poly \[$Relationship\]>>"
            }
        }
    
        lappend uml "@enduml"
    
        return [join $uml "\n"]
    }
    method seqDiagConfig {args} {
        if {[llength $args] % 2 != 0} {
            my Throw "options must be given as name / value pairs, got \"$args\""
        }
        my variable seqDiagConfig
    
        foreach {optname optvalue} $args {
            if {[dict exists $seqDiagConfig $optname]} {
                dict set seqDiagConfig $optname $optvalue
            } else {
                my Throw "unknown sequence diagram option, \"$optname\""
            }
        }
    
        return $seqDiagConfig
    }
    method seqDiagToChan {channel {begin 1} {finish end}} {
        chan puts $channel [my seqDiag $begin $finish]
        return
    }
    method seqDiagToFile {file {begin 1} {finish end}} {
        set channel [open $file w]
        try {
            my seqDiagToChan $channel $begin $finish
        } finally {
            chan close $channel
        }
        return
    }
    method instr {args} {
        return [my Command instr {*}$args]
    }
    method waitForInstrTrace {args} {
        my variable instrReceived
        my variable instrSyncVar
    
        set expect $args
        while {true} {
            while {[$instrReceived size] != 0} {
                set actual [$instrReceived get]
    
                if {[my MatchTrace $actual $expect]} {
                    return $actual
                } else {
                    log::debug "discarding trace, \"$actual\":\
                            failed to match, \"$expect\""
                }
            }
    
            set resolvedVarName [my varname instrSyncVar]
            set timer [expr {$timeout > 0 ?\
                [after $timeout [list set $resolvedVarName TIMEOUT]] : {}}]
            vwait $resolvedVarName
    
            if {$instrSyncVar eq "TIMEOUT"} {
                my Throw "timed out on receiving event traces"
            } elseif {$instrSyncVar eq "FATAL"} {
                my Throw "fatal run-time error"
            } else {
                if {$timer ne {}} {
                    after cancel $timer
                }
            }
        }
    }
    method clearInstrTraceCache {} {
        my variable instrReceived
        while {[$instrReceived size] != 0} {
            $instrReceived get
        }
    }
    method formatInstrTraces {{begin 1} {finish end}} {
        set listing [list]
        set instrs [my RestrictTraces $begin $finish Instrumentation]
    
        relation foreach instr $instrs -ascending TraceId {
            relation assign $instr
            lappend listing [format "% 3u %s: %s" $TraceId $Time $Message]
        }
    
        return [join $listing "\n"]
    }
    method discardInstrTraces {} {
        my variable instrId
        set instrId 0
        relvar eval {
            relvar set Instrumentation [relation empty [relvar set Instrumentation]]
        }
        return
    }
    method instrNotify {args} {
        my variable instrPrefix
        if {[llength $args] == 1} {
            set instrPrefix [lindex $args 0]
        } elseif {[llength $args] > 1} {
            my Throw "wrong number of arguments"
        }
        return $instrPrefix
    }
    method NotifyInstrArrived {instr} {
        my variable instrPrefix
        if {$instrPrefix eq {}} {
            return
        }
    
        try {
            eval [linsert $instrPrefix end $instr]
        } on error {result} {
            log::error "error notifying instrumentation arrival: \"$result\""
            set instrPrefix {}
        }
    }
    method waitForFatalTrace {args} {
        my variable fatalReceived
        my variable fatalSyncVar
    
        set expect $args
        while {true} {
            while {[$fatalReceived size] != 0} {
                set actual [$fatalReceived get]
    
                if {[my MatchTrace $actual $expect]} {
                    return $actual
                } else {
                    log::debug "discarding trace, \"$actual\":\
                            failed to match, \"$expect\""
                }
            }
    
            set resolvedVarName [my varname fatalSyncVar]
            set timer [expr {$timeout > 0 ?\
                [after $timeout [list set $resolvedVarName TIMEOUT]] : {}}]
            vwait $resolvedVarName
    
            if {$fatalSyncVar eq "TIMEOUT"} {
                my Throw "timed out on receiving event traces"
            } else {
                if {$timer ne {}} {
                    after cancel $timer
                }
            }
        }
    }
    method clearFatalTraceCache {} {
        my variable fatalReceived
        while {[$fatalReceived size] != 0} {
            $fatalReceived get
        }
    }
    method formatFatalTraces {{begin 1} {finish end}} {
        set listing [list]
        set fatals [my RestrictTraces $begin $finish Fatal]
    
        relation foreach fatal $fatals -ascending TraceId {
            relation assign $fatal
            lappend listing [format "% 3u %s: %s" $TraceId $Time $Message]
        }
    
        return [join $listing "\n"]
    }
    method discardFatalTraces {} {
        variable fatalId
        set fatalId 0
        relvar eval {
            relvar set Fatal [relation empty [relvar set Fatal]]
        }
        return
    }
    method fatalNotify {args} {
        my variable fatalPrefix
        if {[llength $args] == 1} {
            set fatalPrefix [lindex $args 0]
        } elseif {[llength $args] > 1} {
            my Throw "wrong number of arguments"
        }
        return $fatalPrefix
    }
    method NotifyFatalArrived {fatal} {
        my variable fatalPrefix
        if {$fatalPrefix eq {}} {
            return
        }
    
        try {
            eval [linsert $fatalPrefix end $fatal]
        } on error {result} {
            log::error "error notifying fatal error arrival: \"$result\""
            set fatalPrefix {}
        }
    }
    method saveTraces {file {how ral}} {
        switch -exact -- $how {
            ral {
                serializeToFile $file [self namespace]::*
            }
            sqlite {
                storeToSQLite $file [self namespace]::*
            }
            default {
                my Throw "unknown trace file type, \"$how\""
            }
        }
        return
    }
    method Puts {cmd} {
        log::debug "harness command: \"$cmd\""
        puts $connection $cmd
    }
    method HandleHarnessInput {} {
        set line {}
        for {set gotline false} {!$gotline} {set gotline [string is list $line]} {
            set llen [chan gets $connection input]
            if {$llen == -1} {
                if {[chan eof $connection]} {
                    log::warn "EOF on harness input -- closing \"$connection\""
                    chan close $connection
                    unset -nocomplain connection
                    return
                } elseif {[chan blocked $connection]} {
                    log::notice "partial line received"
                }
            } else {
                append line $input
            }
        }
        if {[string length $line] != 0} {
            log::debug "harness response: \"$line\""
        
            lassign $line resp_type resp_value
        
            switch -exact -- $resp_type {
                cmd {
                    my HandleCmdResponse $resp_value
                }
                trace {
                    my HandleTraceResponse $resp_value
                }
                fatal {
                    my HandleFatalResponse $resp_value
                }
                instr {
                    my HandleInstrResponse $resp_value
                }
                default {
                    my Throw "unknown response type, \"$resp_value\""
                }
            }
        }
    }
    method HandleCmdResponse {respValue} {
        set [my varname cmdSyncVar] $respValue
        return
    }
    method HandleTraceResponse {respValue} {
        my variable traceId
        incr traceId
    
        relvar eval {
            switch -exact -- [dict get $respValue type] {
                transition {
                    relvar insert TransitionTrace [list\
                        TraceId     $traceId\
                        Current     [dict get $respValue currstate]\
                        New         [dict get $respValue newstate]\
                    ]
                }
                polymorphic {
                    relvar insert PolymorphicTrace [list\
                        TraceId         $traceId\
                        Relationship    [dict get $respValue relationship]\
                        NewEvent        [dict get $respValue newevent]\
                        Subclass        [dict get $respValue subclass]\
                    ]
                }
                creation {
                    relvar insert CreationTrace [list\
                        TraceId     $traceId\
                    ]
                }
                default {
                    log::error "unknown state machine trace type,\
                            \"[dict get $respValue type]\""
                    incr traceId -1
                    return                                              ; # <1>
                }
            }
    
            relvar insert Trace [list\
                TraceId     $traceId\
                Time        [dict get $respValue time]\
                Event       [dict get $respValue event]\
                Source      [dict get $respValue source]\
                Target      [dict get $respValue target]\
            ]
        }
    
        my variable tracesReceived
        $tracesReceived put $respValue
        set [my varname traceSyncVar] TRACE
    
        my NotifyTraceArrived $respValue
    
        return
    }
    method HandleInstrResponse {respValue} {
        variable instrReceived
        $instrReceived put $respValue
    
        variable instrId
        incr instrId
        relvar insert Instrumentation [list\
            TraceId     $instrId\
            Time        [dict get $respValue time]\
            Message     [dict get $respValue message]\
        ]
    
        set [my varname instrSyncVar] INSTR
    
        my NotifyInstrArrived $respValue
    
        return
    }
    method HandleFatalResponse {respValue} {
        my variable fatalReceived
        $fatalReceived put $respValue
    
        variable fatalId
        incr fatalId
        relvar insert Fatal [list\
            TraceId     $fatalId\
            Time        [dict get $respValue time]\
            Message     [dict get $respValue message]\
        ]
    
        log::error "received fatal error response, \"$respValue\""
        set [my varname fatalSyncVar] FATAL
        set [my varname cmdSyncVar] FATAL
        set [my varname traceSyncVar] FATAL
    
        my NotifyFatalArrived $respValue
    
        return
    }
    method Command {args} {
        set resolvedVarName [my varname cmdSyncVar]
        set timer [expr {$timeout > 0 ?\
            [after $timeout [list set $resolvedVarName TIMEOUT]] : {}}]
    
        my Puts $args                                   ; # <1>
    
        vwait $resolvedVarName                          ; # <2>
    
        set cmdName [lindex $args 0]
        my variable cmdSyncVar
    
        if {$cmdSyncVar eq "TIMEOUT"} {
            my Throw "timeout for command, \"$cmdName\""
        } elseif {$cmdSyncVar eq "FATAL"} {
            my Throw "fatal run-time error while executing, \"$cmdName\""
        } else {
            if {$timer ne {}} {
                after cancel $timer
            }
        }
    
        if {[dict get $cmdSyncVar name] ne $cmdName} {
            my Throw "expected response for command,\
                    \"$cmdName\",\
                    got, \"[dict get $cmdSyncVar name]\""
        }
    
        set result [dict get $cmdSyncVar result]        ; # <3>
        if {[dict get $cmdSyncVar status] eq "error"} {
            my Throw $result
        }
    
        return $result
    }
    method Throw {message} {
        tailcall uplevel 1 [list throw [list {*}[self caller] $message] $message]
    }
}
proc ::mecate::eventTraceFormat {trace} {
    dict with trace {
        switch -exact -- $type {
            transition {
                return [format\
                    "%s: Transition: %s - %s -> %s: %s ==> %s"\
                    $time $source $event $target $currstate $newstate\
                ]
            }
            polymorphic {
                return [format\
                    "%s: Polymorphic: %s - %s -> %s: %s - %s -> %s"\
                    $time $source $event $target $relationship $newevent\
                    $subclass\
                ]
            }
            creation {
                return [format\
                    "%s: Creation: %s - %s -> %s"\
                    $time $source $event $target\
                ]
            }
            default {
                my Throw "unknown trace type, \"$type\""
            }
        }
    }
}
proc ::mecate::instrTraceFormat {trace} {
    dict with trace {
        return [format "%s: Instr: %s" $time $message]
    }
}
proc ::mecate::fatalTraceFormat {trace} {
    dict with trace {
        return [format "%s: Fatal: %s" $time $message]
    }
}

package provide mecate $::mecate::version
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<












































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Added packages/package-mecate-1.2.1-tcl.tm.









































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
# ACTIVESTATE TEAPOT-PKG BEGIN TM -*- tcl -*-
# -- Tcl Module

# @@ Meta Begin
# Package mecate 1.2.1
# Meta description Mecate is a package that provides a set of command to
# Meta description interact with bosal generated test harnesses.
# Meta platform    tcl
# Meta require     {Tcl 8.6}
# Meta require     logger
# Meta require     oo::util
# Meta require     ral
# Meta require     ralutil
# Meta require     struct::queue
# Meta summary     Command interface to bosal generated test harnesses.
# @@ Meta End


# ACTIVESTATE TEAPOT-PKG BEGIN REQUIREMENTS

package require Tcl 8.6
package require logger
package require oo::util
package require ral
package require ralutil
package require struct::queue

# ACTIVESTATE TEAPOT-PKG END REQUIREMENTS

# ACTIVESTATE TEAPOT-PKG BEGIN DECLARE

package provide mecate 1.2.1

# ACTIVESTATE TEAPOT-PKG END DECLARE
# ACTIVESTATE TEAPOT-PKG END TM
# DO NOT EDIT THIS FILE!
# THIS FILE IS AUTOMATICALLY GENERATED FROM A LITERATE PROGRAM SOURCE FILE.
#
# This software is copyrighted 2018 by G. Andrew Mangogna.
# The following terms apply to all files associated with the software unless
# explicitly disclaimed in individual files.
# 
# The authors hereby grant permission to use, copy, modify, distribute,
# and license this software and its documentation for any purpose, provided
# that existing copyright notices are retained in all copies and that this
# notice is included verbatim in any distributions. No written agreement,
# license, or royalty fee is required for any of the authorized uses.
# Modifications to this software may be copyrighted by their authors and
# need not follow the licensing terms described here, provided that the
# new terms are clearly indicated on the first page of each file where
# they apply.
# 
# IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
# DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING
# OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES
# THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
# 
# THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE
# IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE
# NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS,
# OR MODIFICATIONS.
# 
# GOVERNMENT USE: If you are acquiring this software on behalf of the
# U.S. government, the Government shall have only "Restricted Rights"
# in the software and related documentation as defined in the Federal
# Acquisition Regulations (FARs) in Clause 52.227.19 (c) (2).  If you
# are acquiring the software on behalf of the Department of Defense,
# the software shall be classified as "Commercial Computer Software"
# and the Government shall have only "Restricted Rights" as defined in
# Clause 252.227-7013 (c) (1) of DFARs.  Notwithstanding the foregoing,
# the authors grant the U.S. Government and others acting in its behalf
# permission to use and distribute the software in accordance with the
# terms specified in this license.
#

package require Tcl 8.6
package require logger
package require logger::utils
package require logger::appender
package require ral
package require ralutil
package require oo::util
package require struct::queue

namespace eval ::mecate {
    namespace export rein
    namespace export eventTraceFormat
    namespace export instrTraceFormat
    namespace export fatalTraceFormat
    namespace ensemble create

    set logger [::logger::init mecate]
    set appenderType [expr {[dict exist [fconfigure stdout] -mode] ?\
            "colorConsole" : "console"}]
    ::logger::utils::applyAppender -appender $appenderType -serviceCmd $logger\
            -appenderArgs {-conversionPattern {\[%c\] \[%p\] '%m'}}
    ::logger::import -all -force -namespace log mecate

    variable version 1.2.1
}

::oo::class create ::mecate::rein {
    constructor {args} {
        ::logger::import -all -namespace log mecate
    
        set timeout 2000
        foreach {option value} $args {
            switch -exact -- $option {
                -timeout {
                    set timeout $value
                }
                default {
                    my Throw "unknown option, \"$option\""
                }
            }
        }
    
        log::debug "-timeout option = \"$timeout\""
    
        my variable tracesReceived
        set tracesReceived [::struct::queue]
    
        my variable instrReceived
        set instrReceived [::struct::queue]
    
        my variable fatalReceived
        set fatalReceived [::struct::queue]
    
        my variable tracePrefix
        set tracePrefix {}
        my variable instrPrefix
        set instrPrefix {}
        my variable fatalPrefix
        set fatalPrefix {}
    
        my variable seqDiagConfig
        set seqDiagConfig [dict create\
            -showstates false\
            -participants {}\
        ]
    
        namespace import ::ral::*
        namespace import ::ralutil::*
    
        relvar create Trace {
            TraceId     int
            Time        string
            Event       string
            Source      string
            Target      string
        } TraceId
        
        relvar create TransitionTrace {
            TraceId     int
            Current     string
            New         string
        } TraceId
        
        relvar create PolymorphicTrace {
            TraceId         int
            Relationship    string
            NewEvent        string
            Subclass        string
        } TraceId
        
        relvar create CreationTrace {
            TraceId         int
        } TraceId
        
        relvar partition R1 Trace TraceId\
            TransitionTrace TraceId\
            PolymorphicTrace TraceId\
            CreationTrace TraceId
        relvar create Instrumentation {
            TraceId     int
            Time        string
            Message     string
        } TraceId
        relvar create Fatal {
            TraceId     int
            Time        string
            Message     string
        } TraceId
    
        return
    }
    variable timeout connection
    destructor {
        my disconnect
    
        my variable tracesReceived
        $tracesReceived destroy
    
        my variable instrReceived
        $instrReceived destroy
    
        my variable fatalReceived
        $fatalReceived destroy
    
        relvar constraint delete R1
        relvar unset Trace TransitionTrace PolymorphicTrace CreationTrace\
                Instrumentation Fatal
    }
    method cget {option} {
        switch -exact -- $option {
            -timeout {
                return [set [string range $option 1 end]]
            }
    
            default {
                my Throw "unknown option, \"$option\""
            }
        }
    }
    method configure {args} {
        foreach {option value} $args {
            switch -exact -- $option {
                -timeout {
                    set [string range $option 1 end] $value
                }
    
                default {
                    my Throw "unknown option, \"$option\""
                }
            }
        }
    
        return
    }
    method start {program {delay 500}} {
        log::info "starting harness program, \"$program\""
        set progargs [auto_execok $program]
        if {$progargs eq {}} {
            my Throw "unknown program, \"$program\""
        }
        set pid [exec -ignorestderr -- $progargs &]
        after $delay
        return $pid
    }
    method connect {{port 3906}} {
        log::info "connecting to localhost:$port"
    
        set tries 0                                                             ; # <1>
        while {true} {
            try {
                set connection [socket localhost $port]
                chan configure $connection -blocking true -buffering line
                chan event $connection readable [mymethod HandleHarnessInput]   ; # <2>
                return
            } on error {result opts} {
                incr tries
                if {$tries >= 3} {
                    log::error "connection failure after $tries attempts"
                    return -options $opts $result
                }
                log::notice "connection attempt failed, waiting 500 ms to try again"
                after 500
            }
        }
    }
    method disconnect {} {
        log::info "disconnecting from test harness"
        if {[info exists connection]} {
            catch {chan close $connection}
            unset -nocomplain connection
        }
        return
    }
    method null {} {
        return [my Command null]                ; # <1>
    }
    method version {} {
        return [my Command version]
    }
    method query {what args} {
        return [my Command query $what {*}$args]
    }
    method domainop {domain opname args} {
        return [my Command domainop $domain $opname {*}$args]
    }
    method create {domain class} {
        return [my Command create $domain $class]
    }
    method delete {domain class inst} {
        return [my Command delete $domain $class $inst]
    }
    method read {domain class inst args} {
        return [my Command read $domain $class $inst {*}$args]
    }
    method update {domain class inst args} {
        return [my Command update $domain $class $inst {*}$args]
    }
    method signal {domain class inst event args} {
        return [my Command signal $domain $class $inst $event {*}$args]
    }
    method delaysignal {domain class inst delay event args} {
        return [my Command delaysignal $domain $class $inst $delay $event {*}$args]
    }
    method cancel {domain class inst event} {
        return [my Command cancel $domain $class $inst $event]
    }
    method remaining {domain class inst event} {
        return [my Command remaining $domain $class $inst $event]
    }
    method createasync {domain class event args} {
        return [my Command createasync $domain $class $event {*}$args]
    }
    method eloop {args} {
        return [my Command eloop {*}$args]
    }
    method trace {args} {
        return [my Command trace {*}$args]
    }
    method waitForEventTrace {args} {
        my variable tracesReceived
        my variable traceSyncVar
    
        set expect $args
        while {true} {
            while {[$tracesReceived size] != 0} {
                set actual [$tracesReceived get]
    
                if {[my MatchTrace $actual $expect]} {
                    return $actual
                } else {
                    log::debug "discarding trace, \"$actual\":\
                            failed to match, \"$expect\""
                }
            }
    
            set resolvedVarName [my varname traceSyncVar]
            set timer [expr {$timeout > 0 ?\
                [after $timeout [list set $resolvedVarName TIMEOUT]] : {}}]
            vwait $resolvedVarName
    
            if {$traceSyncVar eq "TIMEOUT"} {
                my Throw "timed out on receiving event traces"
            } elseif {$traceSyncVar eq "FATAL"} {
                my Throw "fatal run-time error"
            } else {
                if {$timer ne {}} {
                    after cancel $timer
                }
            }
        }
    }
    method MatchTrace {trace pattern} {
        set matchCount 0
        dict for {key value} $pattern {
            if {[dict exists $trace $key] &&\
                    [string match $value [dict get $trace $key]]} {
                incr matchCount
            }
        }
    
        return [expr {$matchCount == [dict size $pattern] ? "true" : "false"}]
    }
    method clearEventTraceCache {} {
        my variable tracesReceived
        while {[$tracesReceived size] != 0} {
            $tracesReceived get
        }
        return
    }
    method formatEventTraces {{begin 1} {finish end}} {
        set traces [pipe {
            my RestrictTraces $begin $finish Trace |
            rvajoin ~ [relvar set TransitionTrace] Transition |
            rvajoin ~ [relvar set PolymorphicTrace] Polymorphic |
            rvajoin ~ [relvar set CreationTrace] Creation
        }]                                                      ; # <1>
    
        set listing [list]                                      ; # <2>
        relation foreach trace $traces -ascending TraceId {
            relation assign $trace
            set line {}
            append line [format "% 3u " $TraceId]
            if {[relation isnotempty $Transition]} {
                relation assign $Transition Current New
    
                append line [format\
                    "%s: Transition: %s - %s -> %s: %s ==> %s"\
                    $Time $Source $Event $Target $Current $New\
                ]
            } elseif {[relation isnotempty $Polymorphic]} {
                relation assign $Polymorphic Relationship NewEvent Subclass
    
                append line [format\
                    "%s: Polymorphic: %s - %s -> %s: %s - %s -> %s"\
                    $Time $Source $Event $Target $Relationship $NewEvent $Subclass\
                ]
            } elseif {[relation isnotempty $Creation]} {
                append line [format\
                    "%s: Creation: %s - %s -> %s"\
                    $Time $Source $Event $Target\
                ]
            }
    
            lappend listing $line
        }
    
        return [join $listing "\n"]
    }
    method RestrictTraces {begin finish which} {
        if {$begin == 1 && $finish eq "end"} {                  ; #  <1>
            set traces [relvar set $which]
        } else {
            if {$finish eq "end"} {
                set finish [relation cardinality [relvar set $which]]
            } elseif {![string is integer $finish]} {
                my Throw "bad finish value, \"$finish\""
            }
            set traces [relation restrictwith [relvar set $which]\
                    {$TraceId >= $begin && $TraceId <= $finish}]
        }
        return $traces
    }
    method discardEventTraces {} {
        variable traceId
        set traceId 0                   ; # <1>
        relvar eval {
            relvar set Trace [relation empty [relvar set Trace]]
            relvar set TransitionTrace [relation empty [relvar set TransitionTrace]]
            relvar set PolymorphicTrace [relation empty [relvar set PolymorphicTrace]]
            relvar set CreationTrace [relation empty [relvar set CreationTrace]]
        }                               ; # <2>
        return
    }
    method traceNotify {args} {
        my variable tracePrefix
        if {[llength $args] == 1} {
            set tracePrefix [lindex $args 0]
        } elseif {[llength $args] > 1} {
            my Throw "wrong number of arguments"
        }
        return $tracePrefix
    }
    method NotifyTraceArrived {trace} {
        my variable tracePrefix
        if {$tracePrefix eq {}} {
            return
        }
    
        try {
            eval [linsert $tracePrefix end $trace]
        } on error {result} {
            log::error "error notifying trace arrival: \"$result\""
            set tracePrefix {}                                          ; # <1>
        }
    }
    method seqDiag {{begin 1} {finish end}} {
        my variable seqDiagConfig
        lappend uml "@startuml"
        lappend uml "!pragma teoz true"
    
        set traces [my RestrictTraces $begin $finish Trace]
    
        set participants [dict get $seqDiagConfig -participants]
        if {[llength $participants] == 0} {
            set srcInsts [pipe {
                relation project $traces TraceId Source |
                relation rename ~ Source Name
            }] ;                                                                    # <1>
            set trgInsts [pipe {
                relation project $traces TraceId Target |
                relation rename ~ Target Name |
                relation update ~ t {1} {
                    tuple update $t TraceId [expr {[tuple extract $t TraceId] + 1}]}
            }] ;                                                                    # <2>
            set insts [pipe {
                relation union $srcInsts $trgInsts |
                relation summarizeby ~ Name s First int {rmin($s, "TraceId")} |
                relation list ~ Name -ascending First
            }] ;                                                                    # <3>
        } else {
            set insts $participants
        }
    
        set extlabel BOUNDARY ;        # <1>
        set bdindex [lsearch -exact $insts {?.?}]
        if {$bdindex != -1} {
            set insts [lreplace $insts $bdindex $bdindex $extlabel]
        }
        foreach inst $insts {
            set ptype [expr {$inst eq $extlabel ? "boundary" : "participant"}]
            lappend uml "$ptype \"$inst\""
        }
    
        if {[dict get $seqDiagConfig -showstates]} {
            set initialTransitions [pipe {
                relation join $traces [relvar set TransitionTrace] |
                relation summarizeby ~ Target s TraceId int {rmin($s, "TraceId")} |
                relation join ~ [relvar set TransitionTrace]
            }] ;                                                                      # <1>
            
            set initialStatePrefix {} ;
            relation foreach trans $initialTransitions {
                relation assign $trans
                if {$Target ni $insts} {
                    continue
                }
                if {$Current ne "@"} {
                    lappend uml "$initialStatePrefix rnote over \"$Target\" : $Current" ; # <2>
                    set initialStatePrefix & ;                                         # <3>
                }
            }
        }
    
        set traces [pipe {
            rvajoin $traces [relvar set TransitionTrace] Transition |
            rvajoin ~ [relvar set PolymorphicTrace] Polymorphic |
            rvajoin ~ [relvar set CreationTrace] Creation
        }]
    
        relation foreach trace $traces -ascending TraceId {
            relation assign $trace
    
            if {$Source eq "?.?"} {
                set Source $extlabel
            }
    
            if {!($Source in $insts && $Target in $insts)} {
                continue
            }
    
            if {[relation isnotempty $Transition]} {
                relation assign $Transition
                lappend uml "\"$Source\" --> \"$Target\" : $Event"
                if {[dict get $seqDiagConfig -showstates]} {
                    switch -exact -- $New {
                        CH {
                            lappend uml "hnote over \"$Target\" #red : Can't Happen!"
                        }
                        IG {
                            lappend uml "hnote over \"$Target\" #yellow : Ignored"
                        }
                        default {
                            lappend uml "rnote over \"$Target\" : $New"
                        }
                    }
                }
            } elseif {[relation isnotempty $Creation]} {
                lappend uml "create \"$Target\""
                lappend uml "\"$Source\" -> \"$Target\" : $Event <<create>>"
            } elseif {[relation isnotempty $Polymorphic]} {
                relation assign $Polymorphic
                lappend uml "\"$Source\" --> \"$Target\" :\
                        $Event <<poly \[$Relationship\]>>"
            }
        }
    
        lappend uml "@enduml"
    
        return [join $uml "\n"]
    }
    method seqDiagConfig {args} {
        if {[llength $args] % 2 != 0} {
            my Throw "options must be given as name / value pairs, got \"$args\""
        }
        my variable seqDiagConfig
    
        foreach {optname optvalue} $args {
            if {[dict exists $seqDiagConfig $optname]} {
                dict set seqDiagConfig $optname $optvalue
            } else {
                my Throw "unknown sequence diagram option, \"$optname\""
            }
        }
    
        return $seqDiagConfig
    }
    method seqDiagToChan {channel {begin 1} {finish end}} {
        chan puts $channel [my seqDiag $begin $finish]
        return
    }
    method seqDiagToFile {file {begin 1} {finish end}} {
        set channel [open $file w]
        try {
            my seqDiagToChan $channel $begin $finish
        } finally {
            chan close $channel
        }
        return
    }
    method instr {args} {
        return [my Command instr {*}$args]
    }
    method waitForInstrTrace {args} {
        my variable instrReceived
        my variable instrSyncVar
    
        set expect $args
        while {true} {
            while {[$instrReceived size] != 0} {
                set actual [$instrReceived get]
    
                if {[my MatchTrace $actual $expect]} {
                    return $actual
                } else {
                    log::debug "discarding trace, \"$actual\":\
                            failed to match, \"$expect\""
                }
            }
    
            set resolvedVarName [my varname instrSyncVar]
            set timer [expr {$timeout > 0 ?\
                [after $timeout [list set $resolvedVarName TIMEOUT]] : {}}]
            vwait $resolvedVarName
    
            if {$instrSyncVar eq "TIMEOUT"} {
                my Throw "timed out on receiving event traces"
            } elseif {$instrSyncVar eq "FATAL"} {
                my Throw "fatal run-time error"
            } else {
                if {$timer ne {}} {
                    after cancel $timer
                }
            }
        }
    }
    method clearInstrTraceCache {} {
        my variable instrReceived
        while {[$instrReceived size] != 0} {
            $instrReceived get
        }
    }
    method formatInstrTraces {{begin 1} {finish end}} {
        set listing [list]
        set instrs [my RestrictTraces $begin $finish Instrumentation]
    
        relation foreach instr $instrs -ascending TraceId {
            relation assign $instr
            lappend listing [format "% 3u %s: %s" $TraceId $Time $Message]
        }
    
        return [join $listing "\n"]
    }
    method discardInstrTraces {} {
        my variable instrId
        set instrId 0
        relvar eval {
            relvar set Instrumentation [relation empty [relvar set Instrumentation]]
        }
        return
    }
    method instrNotify {args} {
        my variable instrPrefix
        if {[llength $args] == 1} {
            set instrPrefix [lindex $args 0]
        } elseif {[llength $args] > 1} {
            my Throw "wrong number of arguments"
        }
        return $instrPrefix
    }
    method NotifyInstrArrived {instr} {
        my variable instrPrefix
        if {$instrPrefix eq {}} {
            return
        }
    
        try {
            eval [linsert $instrPrefix end $instr]
        } on error {result} {
            log::error "error notifying instrumentation arrival: \"$result\""
            set instrPrefix {}
        }
    }
    method waitForFatalTrace {args} {
        my variable fatalReceived
        my variable fatalSyncVar
    
        set expect $args
        while {true} {
            while {[$fatalReceived size] != 0} {
                set actual [$fatalReceived get]
    
                if {[my MatchTrace $actual $expect]} {
                    return $actual
                } else {
                    log::debug "discarding trace, \"$actual\":\
                            failed to match, \"$expect\""
                }
            }
    
            set resolvedVarName [my varname fatalSyncVar]
            set timer [expr {$timeout > 0 ?\
                [after $timeout [list set $resolvedVarName TIMEOUT]] : {}}]
            vwait $resolvedVarName
    
            if {$fatalSyncVar eq "TIMEOUT"} {
                my Throw "timed out on receiving event traces"
            } else {
                if {$timer ne {}} {
                    after cancel $timer
                }
            }
        }
    }
    method clearFatalTraceCache {} {
        my variable fatalReceived
        while {[$fatalReceived size] != 0} {
            $fatalReceived get
        }
    }
    method formatFatalTraces {{begin 1} {finish end}} {
        set listing [list]
        set fatals [my RestrictTraces $begin $finish Fatal]
    
        relation foreach fatal $fatals -ascending TraceId {
            relation assign $fatal
            lappend listing [format "% 3u %s: %s" $TraceId $Time $Message]
        }
    
        return [join $listing "\n"]
    }
    method discardFatalTraces {} {
        variable fatalId
        set fatalId 0
        relvar eval {
            relvar set Fatal [relation empty [relvar set Fatal]]
        }
        return
    }
    method fatalNotify {args} {
        my variable fatalPrefix
        if {[llength $args] == 1} {
            set fatalPrefix [lindex $args 0]
        } elseif {[llength $args] > 1} {
            my Throw "wrong number of arguments"
        }
        return $fatalPrefix
    }
    method NotifyFatalArrived {fatal} {
        my variable fatalPrefix
        if {$fatalPrefix eq {}} {
            return
        }
    
        try {
            eval [linsert $fatalPrefix end $fatal]
        } on error {result} {
            log::error "error notifying fatal error arrival: \"$result\""
            set fatalPrefix {}
        }
    }
    method saveTraces {file {how ral}} {
        switch -exact -- $how {
            ral {
                serializeToFile $file [self namespace]::*
            }
            sqlite {
                storeToSQLite $file [self namespace]::*
            }
            default {
                my Throw "unknown trace file type, \"$how\""
            }
        }
        return
    }
    method Puts {cmd} {
        log::debug "harness command: \"$cmd\""
        puts $connection $cmd
    }
    method HandleHarnessInput {} {
        set line {}
        for {set gotline false} {!$gotline} {set gotline [string is list $line]} {
            set llen [chan gets $connection input]
            if {$llen == -1} {
                if {[chan eof $connection]} {
                    log::warn "EOF on harness input -- closing \"$connection\""
                    chan close $connection
                    unset -nocomplain connection
                    return
                } elseif {[chan blocked $connection]} {
                    log::notice "partial line received"
                }
            } else {
                append line $input
            }
        }
        if {[string length $line] != 0} {
            log::debug "harness response: \"$line\""
        
            lassign $line resp_type resp_value
        
            switch -exact -- $resp_type {
                cmd {
                    my HandleCmdResponse $resp_value
                }
                trace {
                    my HandleTraceResponse $resp_value
                }
                fatal {
                    my HandleFatalResponse $resp_value
                }
                instr {
                    my HandleInstrResponse $resp_value
                }
                default {
                    my Throw "unknown response type, \"$resp_value\""
                }
            }
        }
    }
    method HandleCmdResponse {respValue} {
        set [my varname cmdSyncVar] $respValue
        return
    }
    method HandleTraceResponse {respValue} {
        my variable traceId
        incr traceId
    
        relvar eval {
            switch -exact -- [dict get $respValue type] {
                transition {
                    relvar insert TransitionTrace [list\
                        TraceId     $traceId\
                        Current     [dict get $respValue currstate]\
                        New         [dict get $respValue newstate]\
                    ]
                }
                polymorphic {
                    relvar insert PolymorphicTrace [list\
                        TraceId         $traceId\
                        Relationship    [dict get $respValue relationship]\
                        NewEvent        [dict get $respValue newevent]\
                        Subclass        [dict get $respValue subclass]\
                    ]
                }
                creation {
                    relvar insert CreationTrace [list\
                        TraceId     $traceId\
                    ]
                }
                default {
                    log::error "unknown state machine trace type,\
                            \"[dict get $respValue type]\""
                    incr traceId -1
                    return                                              ; # <1>
                }
            }
    
            relvar insert Trace [list\
                TraceId     $traceId\
                Time        [dict get $respValue time]\
                Event       [dict get $respValue event]\
                Source      [dict get $respValue source]\
                Target      [dict get $respValue target]\
            ]
        }
    
        my variable tracesReceived
        $tracesReceived put $respValue
        set [my varname traceSyncVar] TRACE
    
        my NotifyTraceArrived $respValue
    
        return
    }
    method HandleInstrResponse {respValue} {
        variable instrReceived
        $instrReceived put $respValue
    
        variable instrId
        incr instrId
        relvar insert Instrumentation [list\
            TraceId     $instrId\
            Time        [dict get $respValue time]\
            Message     [dict get $respValue message]\
        ]
    
        set [my varname instrSyncVar] INSTR
    
        my NotifyInstrArrived $respValue
    
        return
    }
    method HandleFatalResponse {respValue} {
        my variable fatalReceived
        $fatalReceived put $respValue
    
        variable fatalId
        incr fatalId
        relvar insert Fatal [list\
            TraceId     $fatalId\
            Time        [dict get $respValue time]\
            Message     [dict get $respValue message]\
        ]
    
        log::error "received fatal error response, \"$respValue\""
        set [my varname fatalSyncVar] FATAL
        set [my varname cmdSyncVar] FATAL
        set [my varname traceSyncVar] FATAL
    
        my NotifyFatalArrived $respValue
    
        return
    }
    method Command {args} {
        set resolvedVarName [my varname cmdSyncVar]
        set timer [expr {$timeout > 0 ?\
            [after $timeout [list set $resolvedVarName TIMEOUT]] : {}}]
    
        my Puts $args                                   ; # <1>
    
        vwait $resolvedVarName                          ; # <2>
    
        set cmdName [lindex $args 0]
        my variable cmdSyncVar
    
        if {$cmdSyncVar eq "TIMEOUT"} {
            my Throw "timeout for command, \"$cmdName\""
        } elseif {$cmdSyncVar eq "FATAL"} {
            my Throw "fatal run-time error while executing, \"$cmdName\""
        } else {
            if {$timer ne {}} {
                after cancel $timer
            }
        }
    
        if {[dict get $cmdSyncVar name] ne $cmdName} {
            my Throw "expected response for command,\
                    \"$cmdName\",\
                    got, \"[dict get $cmdSyncVar name]\""
        }
    
        set result [dict get $cmdSyncVar result]        ; # <3>
        if {[dict get $cmdSyncVar status] eq "error"} {
            my Throw $result
        }
    
        return $result
    }
    method Throw {message} {
        tailcall uplevel 1 [list throw [list {*}[self caller] $message] $message]
    }
}
proc ::mecate::eventTraceFormat {trace} {
    dict with trace {
        switch -exact -- $type {
            transition {
                return [format\
                    "%s: Transition: %s - %s -> %s: %s ==> %s"\
                    $time $source $event $target $currstate $newstate\
                ]
            }
            polymorphic {
                return [format\
                    "%s: Polymorphic: %s - %s -> %s: %s - %s -> %s"\
                    $time $source $event $target $relationship $newevent\
                    $subclass\
                ]
            }
            creation {
                return [format\
                    "%s: Creation: %s - %s -> %s"\
                    $time $source $event $target\
                ]
            }
            default {
                my Throw "unknown trace type, \"$type\""
            }
        }
    }
}
proc ::mecate::instrTraceFormat {trace} {
    dict with trace {
        return [format "%s: Instr: %s" $time $message]
    }
}
proc ::mecate::fatalTraceFormat {trace} {
    dict with trace {
        return [format "%s: Fatal: %s" $time $message]
    }
}

package provide mecate $::mecate::version