aboutsummaryrefslogtreecommitdiffstats
path: root/messagebus/src/main/java/com/yahoo/messagebus/TraceNode.java
blob: 9eccec8b5c51f21ad12f4d11a37c89bd13185a59 (plain) (blame)
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
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.messagebus;

import java.util.logging.Level;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;

/**
 * This class contains the actual trace information of a {@link Trace} object. A trace node can be encoded to, and
 * decoded from a string representation to allow transport across the network. Each node contains a list of children, a
 * strictness flag and an optional note. The child list is what forms the trace tree, the strictness flag dictates
 * whether or not the ordering of the children is important, and the note is the actual traced data.
 *
 * The most important feature to notice is the {@link #normalize()} method that will compact, sort and 'rootify' the
 * trace tree so that trees become well-formed (and can be compared for equality).
 *
 * @author Simon Thoresen Hult
 */
public class TraceNode implements Comparable<TraceNode> {

    private static final Logger log = Logger.getLogger(TraceNode.class.getName());
    private TraceNode parent = null;
    private boolean strict = true;
    private String note = null;
    private List<TraceNode> children = new ArrayList<>();

    /**
     * Create an empty trace tree.
     */
    public TraceNode() {
        // empty
    }

    /**
     * Create a leaf node with the given note.
     *
     * @param note The note to assign to this.
     */
    private TraceNode(String note) {
        this.note = note;
    }

    /**
     * Create a trace tree which is a copy of another.
     *
     * @param rhs The tree to copy.
     */
    private TraceNode(TraceNode rhs) {
        strict = rhs.strict;
        note = rhs.note;
        addChildren(rhs.children);
    }

    /**
     * Swap the internals of this tree with another.
     *
     * @param other The tree to swap internals with.
     * @return This, to allow chaining.
     */
    public TraceNode swap(TraceNode other) {
        TraceNode parent = this.parent;
        this.parent = other.parent;
        other.parent = parent;

        boolean strict = this.strict;
        this.strict = other.strict;
        other.strict = strict;

        String note = this.note;
        this.note = other.note;
        other.note = note;

        List<TraceNode> children = this.children;
        this.children = other.children;
        for (TraceNode child : this.children) {
            child.parent = this;
        }
        other.children = children;
        for (TraceNode child : other.children) {
            child.parent = other;
        }

        return this;
    }

    /**
     * Remove all trace information from this tree.
     *
     * @return This, to allow chaining.
     */
    public TraceNode clear() {
        parent = null;
        strict = true;
        note = null;
        children.clear();
        return this;
    }

    /**
     * Sort non-strict children recursively down the tree.
     *
     * @return This, to allow chaining.
     */
    public TraceNode sort() {
        if (!isLeaf()) {
            for (TraceNode child : children) {
                child.sort();
            }
            if (!isStrict()) {
                Collections.sort(children);
            }
        }
        return this;
    }

    @Override
    public int compareTo(TraceNode rhs) {
        if (isLeaf() || rhs.isLeaf()) {
            if (isLeaf() && rhs.isLeaf()) {
                return note.compareTo(rhs.getNote());
            } else {
                return isLeaf() ? -1 : 1;
            }
        }
        if (children.size() != rhs.children.size()) {
            return children.size() < rhs.children.size() ? -1 : 1;
        }
        for (int i = 0; i < children.size(); ++i) {
            int cmp = children.get(i).compareTo(rhs.children.get(i));
            if (cmp != 0) {
                return cmp;
            }
        }
        return -1;
    }

    /**
     * Compact this tree. This will reduce the height of this tree as much as possible without removing information
     * stored in it.
     *
     * @return This, to allow chaining.
     */
    public TraceNode compact() {
        if (isLeaf()) {
            return this;
        }
        List<TraceNode> tmp = this.children;
        this.children = new ArrayList<>();
        for (TraceNode child : tmp) {
            child.compact();
            if (child.isEmpty()) {
                // ignore
            } else if (child.isLeaf()) {
                addChild(child);
            } else if (strict == child.strict) {
                addChildren(child.children);
            } else if (child.getNumChildren() == 1) {
                TraceNode grandChild = child.getChild(0);
                if (grandChild.isEmpty()) {
                    // ignore
                } else if (grandChild.isLeaf() || strict != grandChild.strict) {
                    addChild(grandChild);
                } else {
                    addChildren(grandChild.children);
                }
            } else {
                addChild(child);
            }
        }
        return this;
    }

    /**
     * Normalize this tree. This will transform all equivalent trees into the same form. Note that this will also
     * perform an implicit compaction of the tree.
     *
     * @return This, to allow chaining.
     */
    public TraceNode normalize() {
        compact();
        sort();
        if (note != null || !strict) {
            TraceNode child = new TraceNode();
            child.swap(this);
            addChild(child);
            strict = true;
        }
        return this;
    }

    /**
     * Check whether or not this is a root node.
     *
     * @return True if this has no parent.
     */
    public boolean isRoot() {
        return parent == null;
    }

    /**
     * Check whether or not this is a leaf node.
     *
     * @return True if this has no children.
     */
    public boolean isLeaf() {
        return children.isEmpty();
    }

    /**
     * Check whether or not this node is empty, i.e. it has no note and no children.
     *
     * @return True if this node is empty.
     */
    public boolean isEmpty() {
        return note == null && children.isEmpty();
    }

    /**
     * Check whether or not the children of this node are strictly ordered.
     *
     * @return True if this node is strict.
     */
    public boolean isStrict() {
        return strict;
    }

    /**
     * Sets whether or not the children of this node are strictly ordered.
     *
     * @param strict True to order children strictly.
     * @return This, to allow chaining.
     */
    public TraceNode setStrict(boolean strict) {
        this.strict = strict;
        return this;
    }

    /**
     * Returns whether or not a note is assigned to this node.
     *
     * @return True if a note is assigned.
     */
    public boolean hasNote() {
        return note != null;
    }

    /**
     * Returns the note assigned to this node.
     *
     * @return The note.
     */
    public String getNote() {
        return note;
    }

    /**
     * Returns the number of child nodes of this.
     *
     * @return The number of children.
     */
    public int getNumChildren() {
        return children.size();
    }

    /**
     * Returns the child trace node at the given index.
     *
     * @param i The index of the child to return.
     * @return The child at the given index.
     */
    public TraceNode getChild(int i) {
        return children.get(i);
    }

    /**
     * Convenience method to add a child node containing a note to this.
     *
     * @param note The note to assign to the child.
     * @return This, to allow chaining.
     */
    public TraceNode addChild(String note) {
        return addChild(new TraceNode(note));
    }

    /**
     * Adds a child node to this.
     *
     * @param child The child to add.
     * @return This, to allow chaining.
     */
    public TraceNode addChild(TraceNode child) {
        if (note != null) {
            throw new IllegalStateException("Nodes with notes are leaf nodes, you can not add children to it.");
        }
        TraceNode node = new TraceNode(child);
        node.parent = this;
        children.add(node);
        return this;
    }

    /**
     * Adds a list of child nodes to this.
     *
     * @param children The children to add.
     * @return This, to allow chaining.
     */
    public TraceNode addChildren(List<TraceNode> children) {
        for (TraceNode child : children) {
            addChild(child);
        }
        return this;
    }

    // Overrides Object.
    @Override
    public String toString() {
        return toString(Integer.MAX_VALUE);
    }

    /**
     * Generates a non-parseable, human-readable string representation
     * of this trace node.
     *
     * @return generated string
     * @param limit soft limit for maximum string size
     **/
    public String toString(int limit) {
        StringBuilder out = new StringBuilder();
        if (!writeString(out, "", limit)) {
            out.append("...\n");
        }
        return out.toString();
    }

    /**
     * Writes a non-parseable, human-readable string representation of
     * this trace node to the given string builder using the given
     * indent string for every written line.
     *
     * @return false if written string was capped
     * @param ret    The string builder to write to.
     * @param indent The indent to use.
     * @param limit soft limit for maximum string size
     */
    private boolean writeString(StringBuilder ret, String indent, int limit) {
        if (ret.length() >= limit) {
            return false;
        }
        if (note != null) {
            ret.append(indent).append(note).append("\n");
        } else {
            String name = isStrict() ? "trace" : "fork";
            ret.append(indent).append("<").append(name).append(">\n");
            for (TraceNode child : children) {
                if (!child.writeString(ret, indent + "    ", limit)) {
                    return false;
                }
            }
            if (ret.length() >= limit) {
                return false;
            }
            ret.append(indent).append("</").append(name).append(">\n");
        }
        return true;
    }

    /**
     * Returns a parseable (using {@link #decode(String)}) string representation of this trace node.
     *
     * @return A string representation of this tree.
     */
    public String encode() {
        StringBuilder ret = new StringBuilder();
        encode(ret);
        return ret.toString();
    }

    /**
     * Writes a parseable string representation of this trace node to the given string builder.
     *
     * @param ret The string builder to write to.
     */
    private void encode(StringBuilder ret) {
        if (note != null) {
            ret.append("[");
            for (int i = 0, len = note.length(); i < len; ++i) {
                char c = note.charAt(i);
                if (c == '\\' || c == ']') {
                    ret.append('\\');
                }
                ret.append(note.charAt(i));
            }
            ret.append("]");
        } else {
            ret.append(strict ? "(" : "{");
            for (TraceNode child : children) {
                child.encode(ret);
            }
            ret.append(strict ? ")" : "}");
        }
    }

    /**
     * Build a trace tree from the given string representation (possibly encoded using {@link #encode()}).
     *
     * @param str The string to parse.
     * @return The corresponding trace tree, or an empty node if parsing failed.
     */
    public static TraceNode decode(String str) {
        if (str == null || str.isEmpty()) {
            return new TraceNode();
        }
        TraceNode proxy = new TraceNode();
        TraceNode node = proxy;
        StringBuilder note = null;
        boolean inEscape = false;
        for (int i = 0, len = str.length(); i < len; ++i) {
            char c = str.charAt(i);
            if (note != null) {
                if (inEscape) {
                    note.append(c);
                    inEscape = false;
                } else if (c == '\\') {
                    inEscape = true;
                } else if (c == ']') {
                    node.addChild(note.toString());
                    note = null;
                } else {
                    note.append(c);
                }
            } else {
                if (c == '[') {
                    note = new StringBuilder();
                } else if (c == '(' || c == '{') {
                    node.addChild(new TraceNode());
                    node = node.getChild(node.getNumChildren() - 1);
                    node.setStrict(c == '(');
                } else if (c == ')' || c == '}') {
                    if (node == null) {
                        log.log(Level.WARNING, "Unexpected closing brace in trace '" + str + "' at position " + i + ".");
                        return new TraceNode();
                    }
                    if (node.isStrict() != (c == ')')) {
                        log.log(Level.WARNING, "Mismatched closing brace in trace '" + str + "' at position " + i + ".");
                        return new TraceNode();
                    }
                    node = node.parent;
                }
            }
        }
        if (note != null) {
            log.log(Level.WARNING, "Unterminated note in trace '" + str + "'.");
            return new TraceNode();
        }
        if (node != proxy) {
            log.log(Level.WARNING, "Missing closing brace in trace '" + str + "'.");
            return new TraceNode();
        }
        if (proxy.getNumChildren() == 0) {
            log.log(Level.WARNING, "No nodes found in trace '" + str + "'.");
            return new TraceNode();
        }
        if (proxy.getNumChildren() != 1) {
            return proxy; // best-effort recovery from malformed input
        }
        TraceNode ret = proxy.children.remove(0);
        ret.parent = null;
        return ret;
    }
}