blob: beac9f912f0acae8608245104961f4cf393a882d [file] [log] [blame]
khenaidoo43c82122018-11-22 18:38:28 -05001/*
2 * Copyright 2018-present Open Networking Foundation
3
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7
8 * http://www.apache.org/licenses/LICENSE-2.0
9
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package kafka
17
18import (
19 "fmt"
20 "strings"
21)
22
23const (
24 TopicSeparator = "_"
25 DeviceIdLength = 24
26)
27
28// A Topic definition - may be augmented with additional attributes eventually
29type Topic struct {
30 // The name of the topic. It must start with a letter,
31 // and contain only letters (`[A-Za-z]`), numbers (`[0-9]`), dashes (`-`),
32 // underscores (`_`), periods (`.`), tildes (`~`), plus (`+`) or percent
33 // signs (`%`).
34 Name string
35}
36
37type KVArg struct {
38 Key string
39 Value interface{}
40}
41
42//CreateSubTopic concatenate a list of arguments together using underscores.
43func CreateSubTopic(args ...string) Topic {
44 topic := ""
45 for index, arg := range args {
46 if index == 0 {
47 topic = arg
48 } else {
49 topic = fmt.Sprintf("%s%s%s", topic, TopicSeparator, arg)
50 }
51 }
52 return Topic{Name: topic}
53}
54
55// GetDeviceIdFromTopic extract the deviceId from the topic name. The topic name is formatted either as:
56// <any string> or <any string>_<deviceId>. The device Id is 24 characters long.
57func GetDeviceIdFromTopic(topic Topic) string {
58 pos := strings.LastIndex(topic.Name, TopicSeparator)
59 if pos == -1 {
60 return ""
61 }
62 adjustedPos := pos + len(TopicSeparator)
63 if adjustedPos >= len(topic.Name) {
64 return ""
65 }
66 deviceId := topic.Name[adjustedPos:len(topic.Name)]
67 if len(deviceId) != DeviceIdLength {
68 return ""
69 }
70 return deviceId
71}