1
yangle
昨天 6d0bfe2160e06a4502dc3052c43fab9813341db3
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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Threading;
using Taobao.Top.Link.Channel;
using Taobao.Top.Link.Endpoints;
using Taobao.Top.Link.Util;
using Top.Api;
using Top.Api.Util;
 
namespace Top.Tmc
{
    /// <summary>消息服务客户端</summary>
    public class TmcClient
    {
        // sign parameters
        private const string GROUP_NAME = "group_name";
        private const string SDK = "sdk";
        private const string INTRANET_IP = "intranet_ip";
 
        private TmcClientIdentity _id;
        private string _appSecret;
        private string _uri;
        private Endpoint _endpoint;
        private EndpointProxy _serverProxy;
 
        private volatile bool running;
 
        private int _heartbeatInterval = 45000; // 心跳频率(单位:毫秒)
        private int _reconnectIntervalSeconds = 15; // 重连周期(单位:秒)
        private int _pullRequestIntervalSeconds = 30; // 定时获取消息周期(单位:秒)
        private Timer _reconnectTimer;
        private Timer _pullRequestTimer;
 
        public event EventHandler<MessageArgs> OnMessage;
 
        /// <summary>获取或设置Log</summary>
        public ITopLogger Log { get; set; }
 
        private bool enableTraceLog = true;
 
        public bool EnableTraceLog
        {
            get { return this.enableTraceLog;}
            set { this.enableTraceLog = value; }
        }
 
        /// <summary>获取或设置定时发送拉取请求的周期(单位:秒)</summary>
        public int PullRequestIntervalSeconds
        {
            get { return this._pullRequestIntervalSeconds; }
            set
            {
                this._pullRequestIntervalSeconds = value;
                if (this._pullRequestTimer != null)
                    this._pullRequestTimer.Change(TimeSpan.FromSeconds(this._pullRequestIntervalSeconds)
                        , TimeSpan.FromSeconds(this._pullRequestIntervalSeconds));
            }
        }
 
        /// <summary>获取或设置自动重连间隔(单位:秒)</summary>
        public int ReconnectIntervalSeconds
        {
            get { return this._reconnectIntervalSeconds; }
            set
            {
                this._reconnectIntervalSeconds = value;
                if (this._reconnectTimer != null)
                    this._reconnectTimer.Change(TimeSpan.FromSeconds(this._reconnectIntervalSeconds)
                        , TimeSpan.FromSeconds(this._reconnectIntervalSeconds));
            }
        }
 
        /// <summary>以默认分组,初始化TMC客户端</summary>
        public TmcClient(string appKey, string appSecret) : this(appKey, appSecret, "default") { }
 
        /// <summary>初始化TMC客户端</summary>
        public TmcClient(string appKey, string appSecret, string groupName)
        {
            this._appSecret = appSecret;
            this._id = new TmcClientIdentity(appKey, groupName);
            this.PrepareEndpoint();
        }
 
        /// <summary>连接到 TMC Server</summary>
        /// <param name="uri">TMC server address, eg: ws://mc.api.taobao.com/</param>
        public void Connect(string uri)
        {
            this.running = true;
            doConnect(uri);
            this.StartReconnect();
            this.StartPullRequest();
        }
 
        private void doConnect(string uri)
        {
            var signHeader = new Dictionary<string, string>();
            var connHeader = new Dictionary<string, object>();
            signHeader.Add(Constants.APP_KEY, this._id.AppKey);
            connHeader.Add(Constants.APP_KEY, signHeader[Constants.APP_KEY]);
 
            signHeader.Add(GROUP_NAME, this._id.GroupName);
            connHeader.Add(GROUP_NAME, signHeader[GROUP_NAME]);
 
            signHeader.Add(Constants.TIMESTAMP, DateTime.Now.Ticks.ToString());
            connHeader.Add(Constants.TIMESTAMP, signHeader[Constants.TIMESTAMP]);
 
            connHeader.Add(Constants.SIGN, TopUtils.SignTopRequest(signHeader, this._appSecret, Constants.SIGN_METHOD_MD5));
            //extra fields
            connHeader.Add(SDK, Constants.SDK_VERSION);
            connHeader.Add(INTRANET_IP, TopUtils.GetIntranetIp());
            this._serverProxy = this._endpoint.GetEndpoint(new TmcServerIdentity(), uri, connHeader);
            this._uri = uri;
            this.Log.Info("connected to tmc server: {0}", uri);
        }
 
        /// <summary>向指定的主题发布一条与用户无关的消息。</summary>
        /// <param name="topic">主题名称</param>
        /// <param name="content">严格根据主题定义的消息内容(JSON/XML)</param>
        public void Send(string topic, string content)
        {
            if (string.IsNullOrEmpty(topic))
                throw new ArgumentNullException("topic");
            if (string.IsNullOrEmpty(content))
                throw new ArgumentNullException("content");
 
            IDictionary<string, object> msg = new Dictionary<string, object>();
            msg.Add(MessageFields.KIND, MessageKind.Data);
            msg.Add(MessageFields.DATA_TOPIC, topic);
            msg.Add(MessageFields.DATA_CONTENT, content);
            this._serverProxy.SendAndWait(msg, 2000);
        }
 
        /// <summary>向指定的主题发布一条与用户相关的消息。</summary>
        /// <param name="topic">主题名称</param>
        /// <param name="content">严格根据主题定义的消息内容(JSON/XML)</param>
        /// <param name="session">用户授权码</param>
        public void Send(string topic, string content, string session)
        {
            if (string.IsNullOrEmpty(topic))
                throw new ArgumentNullException("topic");
            if (string.IsNullOrEmpty(content))
                throw new ArgumentNullException("content");
            if (string.IsNullOrEmpty(session))
                throw new ArgumentNullException("session");
 
            IDictionary<string, object> msg = new Dictionary<string, object>();
            msg.Add(MessageFields.KIND, MessageKind.Data);
            msg.Add(MessageFields.DATA_TOPIC, topic);
            msg.Add(MessageFields.DATA_CONTENT, content);
            msg.Add(MessageFields.DATA_INCOMING_USER_SESSION, session);
            this._serverProxy.SendAndWait(msg, 2000);
        }
 
        /// <summary>向服务端发送消息拉取请求</summary>
        protected internal void PullRequest()
        {
            IDictionary<string, object> msg = new Dictionary<string, object>();
            msg.Add(MessageFields.KIND, MessageKind.PullRequest);
            this._serverProxy.Send(msg);
        }
 
        /// <summary>确认消息</summary>
        protected internal void Confirm(long id)
        {
            IDictionary<string, object> msg = new Dictionary<string, object>();
            msg.Add(MessageFields.KIND, MessageKind.Confirm);
            msg.Add(MessageFields.CONFIRM_ID, id);
            this._serverProxy.Send(msg);
        }
 
        /// <summary>确认消息</summary>
        protected internal void Fail(long id,string errorMsg)
        {
            IDictionary<string, object> msg = new Dictionary<string, object>();
            msg.Add(MessageFields.KIND, MessageKind.Failed);
            msg.Add(MessageFields.CONFIRM_ID, id);
            msg.Add(MessageFields.CONFIRM_MSG, errorMsg);
 
            this._serverProxy.Send(msg);
        }
 
        private void PrepareEndpoint()
        {
            this.Log = Top.Api.Log.Instance;
            this._endpoint = new Endpoint(Log, this._id);
            this._endpoint.ChannelSelector = new ClientChannelSharedSelector(Log) { HeartbeatPeriod = this._heartbeatInterval };
            this._endpoint.OnMessage += new EventHandler<EndpointContext>(InternalOnMessage);
            this._endpoint.OnAckMessage += new EventHandler<AckMessageArgs>(InternalOnAckMessage);
        }
 
        private void InternalOnMessage(object sender, EndpointContext context)
        {
            if (enableTraceLog)
            {
                this.Log.Info("messsage from {0}: {1}", context.MessageFrom, this.Dump(context.Message));
            }
            
            if (this.OnMessage == null)
                return;
 
            ThreadPool.QueueUserWorkItem(o =>
            {
                if (!this.running)
                {
                    this.Log.Info(string.Format("message dropped as client closed: {0}", this.Dump(context.Message)));
                    return;
                }
 
                Message msg = this.ParseMessage(context.Message);
                var args = new MessageArgs(msg, m => this.Confirm(m.Id));
                var sw = new Stopwatch();
                try
                {
                    sw.Start();
                    this.OnMessage(this, args);
                    sw.Stop();
                }
                catch (Exception e)
                {
                    args.Fail(e.Message);
                }
 
                if (args._isFail)
                {
                    this.Log.Info("process message error: {0}", args._reason);
                    this.Fail(msg.Id,args._reason.Length > 128 ? args._reason.Substring(0,128) : args._reason);
                    return;
                }
 
                // prevent confirm attach
                if (sw.ElapsedMilliseconds <= 1)
                {
                    Thread.Sleep(10);
                }
 
                if (args._isConfirmed){
                    return;
                }
 
                try
                {
                    this.Confirm(msg.Id);
 
                    if (enableTraceLog)
                    {
                        this.Log.Info("confirm message topic: {0}, dataid: {1}", msg.Topic, msg.Dataid);
                    }
                }
                catch (Exception e)
                {
                    this.Log.Warn(string.Format("confirm message {0} error {1}", this.Dump(context.Message), e.StackTrace));
                }
            });
        }
 
        private void InternalOnAckMessage(object sender, AckMessageArgs e)
        {
            if (this.Log.IsDebugEnabled())
                this.Log.Debug("ack messsage from {0}: {1}", e.MessageFrom, e.Message);
        }
 
        private void StartReconnect()
        {
            if (this._reconnectTimer != null) return;
            this._reconnectTimer = new Timer(o =>
            {
                try
                {
                    if (!this._serverProxy.hasValidSender())
                    {
                        this.Log.Info("reconning...");
                        this.doConnect(this._uri);
                    }
                }
                catch (Exception e)
                {
                    this.Log.Warn("reconnect error", e);
                }
            }, null
            , TimeSpan.FromSeconds(this._reconnectIntervalSeconds)
            , TimeSpan.FromSeconds(this._reconnectIntervalSeconds));
        }
 
        private void StartPullRequest()
        {
            if (this._pullRequestTimer != null) return;
            this._pullRequestTimer = new Timer(o =>
            {
                try
                {
                    if (this._serverProxy.hasValidSender())
                    {
                        this.PullRequest();
                    }
                }
                catch (Exception e)
                {
                    this.Log.Warn("pull request error", e);
                }
            }
            , null
            , TimeSpan.FromMilliseconds(500)
            , TimeSpan.FromSeconds(this.PullRequestIntervalSeconds));
        }
 
        private Message ParseMessage(IDictionary<string, object> raw)
        {
            var msg = new Message();
            msg.Id = this.GetValue<long>(raw, MessageFields.OUTGOING_ID);
            msg.Topic = this.GetValue<string>(raw, MessageFields.DATA_TOPIC);
            msg.PubAppKey = this.GetValue<string>(raw, MessageFields.DATA_OUTGOING_PUBLISHER);
            msg.PubTime = this.GetValue<DateTime>(raw, MessageFields.DATA_PUBLISH_TIME);
            msg.UserId = this.GetValue<long>(raw, MessageFields.DATA_OUTGOING_USER_ID);
            msg.UserNick = this.GetValue<string>(raw, MessageFields.DATA_OUTGOING_USER_NICK);
            msg.OutgoingTime = this.GetValue<DateTime>(raw, MessageFields.DATA_ATTACH_OUTGOING_TIME);
            msg.Dataid = this.GetValue<object>(raw, MessageFields.DATA_DATAID);
 
            if (!raw.ContainsKey(MessageFields.DATA_CONTENT))
                return msg;
            msg.Content = raw[MessageFields.DATA_CONTENT] is byte[]
                ? Encoding.UTF8.GetString(GZIPHelper.Unzip(raw[MessageFields.DATA_CONTENT] as byte[]))
                : (string)raw[MessageFields.DATA_CONTENT];
 
            return msg;
        }
 
        private T GetValue<T>(IDictionary<string, object> raw, string key)
        {
            if (raw.ContainsKey(key))
            {
                object value = raw[key];
                if (value != null)
                {
                    return (T)value;
                }
            }
            return default(T);
        }
 
        private string Dump(IDictionary<string, object> raw)
        {
            var buf = new StringBuilder();
            foreach (var i in raw)
                buf.AppendFormat("{0}={1}|", i.Key, i.Value);
            return buf.ToString();
        }
 
        public void Close()
        {
            this.running = false;
            if (this._pullRequestTimer != null)
            {
                this._pullRequestTimer.Dispose();
                this._pullRequestTimer = null;
            }
            if (this._reconnectTimer != null)
            {
                this._reconnectTimer.Dispose();
                this._reconnectTimer = null;
            }
            this._serverProxy.Close(this._uri, "client closed");
            this.Log.Warn("tmc client closed");
        }
 
        public bool Online
        {
            get
            {
                return this._serverProxy != null && this._serverProxy.hasValidSender();
            }
        }
    }
}