-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcontext.go
187 lines (154 loc) · 4.44 KB
/
context.go
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
// MIT License
// Copyright (c) 2023 wetrycode
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
package tegenaria
import (
"context"
"fmt"
"runtime"
"strings"
"time"
"github.com/sirupsen/logrus"
)
// Context 在引擎中的数据流通载体,负责单个抓取任务的生命周期维护
type Context struct {
// Request 请求对象
Request *Request
// Response 响应对象
Response *Response
//parent 父 context
parent context.Context
// CtxID context 唯一id由uuid生成
CtxID string
// Error 处理过程中的错误信息
Error error
// Cancel context.CancelFunc
Cancel context.CancelFunc
// Items 读写item的管道
Items chan *ItemMeta
// Spider 爬虫实例
Spider SpiderInterface
}
// ContextOption 上下文选项
type ContextOption func(c *Context)
// WithContextID 设置自定义的ctxId
func WithContextID(ctxID string) ContextOption {
return func(c *Context) {
c.CtxID = ctxID
}
}
// WithItemChannelSize 设置 items 管道的缓冲大小
func WithItemChannelSize(size int) ContextOption {
return func(c *Context) {
c.Items = make(chan *ItemMeta, size)
}
}
// NewContext 从内存池中构建context对象
func NewContext(request *Request, Spider SpiderInterface, opts ...ContextOption) *Context {
ctx := &Context{}
parent, cancel := context.WithCancel(context.TODO())
ctx.Request = request
ctx.Spider = Spider
ctx.CtxID = GetUUID()
ctx.Cancel = cancel
ctx.Items = make(chan *ItemMeta, 32)
ctx.parent = parent
ctx.Error = nil
log.Infof("Generate a new request%s %s", ctx.CtxID, request.Url)
for _, o := range opts {
o(ctx)
}
return ctx
}
// setResponse 设置响应
func (c *Context) setResponse(resp *Response) {
c.Response = resp
}
// setError 设置异常
func (c *Context) setError(msg string, stack string) {
DebugStack := stack
for _, v := range strings.Split(DebugStack, "\n") {
DebugStack += v
}
err := NewError(c, fmt.Errorf("%s", msg))
c.Error = err
// 取上一帧栈
pc, file, lineNo, _ := runtime.Caller(1)
f := runtime.FuncForPC(pc)
fields := logrus.Fields{
"request_id": c.CtxID,
"func": f.Name(),
"file": fmt.Sprintf("%s:%d", file, lineNo),
"stack": DebugStack,
}
log := engineLog.WithFields(fields)
log.Logger.SetReportCaller(false)
log.Errorf("%s", err.Error())
}
// Close 关闭context
func (c *Context) Close() {
if c.Response != nil {
// 释放response
freeResponse(c.Response)
}
// ctxManager.remove(c)
c.CtxID = ""
c.Cancel()
}
// WithContext 设置父context
func WithContext(ctx context.Context) ContextOption {
return func(c *Context) {
parent, cancel := context.WithCancel(ctx)
c.parent = parent
c.Cancel = cancel
}
}
// Deadline context.Deadline implementation
func (c *Context) Deadline() (deadline time.Time, ok bool) {
if c.Request == nil || c.parent == nil {
return time.Time{}, false
}
return c.parent.Deadline()
}
// Done context.Done implementation
func (c *Context) Done() <-chan struct{} {
if c.Request == nil || c.parent == nil {
return nil
}
return c.parent.Done()
}
// Err context.Err implementation
func (c *Context) Err() error {
if c.Request == nil || c.parent == nil {
return nil
}
return c.parent.Err()
}
// Value context.WithValue implementation
func (c *Context) Value(key interface{}) interface{} {
if key == 0 {
return c.Request
}
if c.Request == nil || c.parent == nil {
return nil
}
return c.parent.Value(key)
}
// GetCtxID get context id
func (c Context) GetCtxID() string {
return c.CtxID
}