|
| 1 | +<?php |
| 2 | +/** |
| 3 | + * Copyright 2017 OpenCensus Authors |
| 4 | + * |
| 5 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | + * you may not use this file except in compliance with the License. |
| 7 | + * You may obtain a copy of the License at |
| 8 | + * |
| 9 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | + * |
| 11 | + * Unless required by applicable law or agreed to in writing, software |
| 12 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | + * See the License for the specific language governing permissions and |
| 15 | + * limitations under the License. |
| 16 | + */ |
| 17 | + |
| 18 | +namespace OpenCensus\Trace\Propagator; |
| 19 | + |
| 20 | +use OpenCensus\Trace\TraceContext; |
| 21 | + |
| 22 | +/** |
| 23 | + * This propagator contains the method for serializaing and deserializing |
| 24 | + * TraceContext over a binary format. |
| 25 | + * |
| 26 | + * See https://github.com/census-instrumentation/opencensus-specs/blob/master/encodings/BinaryEncoding.md |
| 27 | + * for the encoding specification. |
| 28 | + */ |
| 29 | +class BinaryFormatter implements FormatterInterface |
| 30 | +{ |
| 31 | + const OPTION_ENABLED = 1; |
| 32 | + |
| 33 | + /** |
| 34 | + * Generate a TraceContext object from the Trace Context header |
| 35 | + * |
| 36 | + * @param string $header |
| 37 | + * @return TraceContext |
| 38 | + */ |
| 39 | + public function deserialize($bin) |
| 40 | + { |
| 41 | + $data = @unpack('Cversion/Cfield0/H32traceId/Cfield1/H16spanId/Cfield2/Coptions', $bin); |
| 42 | + if ($data === false) { |
| 43 | + trigger_error('Invalid binary format for TraceContext', E_USER_WARNING); |
| 44 | + return new TraceContext(); |
| 45 | + } |
| 46 | + $enabled = !!($data['options'] & self::OPTION_ENABLED); |
| 47 | + return new TraceContext($data['traceId'], hexdec($data['spanId']), $enabled, true); |
| 48 | + } |
| 49 | + |
| 50 | + /** |
| 51 | + * Convert a TraceContext to header string |
| 52 | + * |
| 53 | + * @param TraceContext $context |
| 54 | + * @return string |
| 55 | + */ |
| 56 | + public function serialize(TraceContext $context) |
| 57 | + { |
| 58 | + $spanHex = str_pad(dechex($context->spanId()), 16, "0", STR_PAD_LEFT); |
| 59 | + $traceOptions = $context->enabled() ? self::OPTION_ENABLED : 0; |
| 60 | + return pack("CCH*CH*CC", 0, 0, $context->traceId(), 1, $spanHex, 2, $traceOptions); |
| 61 | + } |
| 62 | +} |
0 commit comments