1
|
|
|
# Licensed to the StackStorm, Inc ('StackStorm') under one or more |
2
|
|
|
# contributor license agreements. See the NOTICE file distributed with |
3
|
|
|
# this work for additional information regarding copyright ownership. |
4
|
|
|
# The ASF licenses this file to You under the Apache License, Version 2.0 |
5
|
|
|
# (the "License"); you may not use this file except in compliance with |
6
|
|
|
# the License. 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
|
|
|
|
16
|
|
|
import pecan |
17
|
|
|
import six |
18
|
|
|
from pecan import Response |
19
|
|
|
from pecan.rest import RestController |
20
|
|
|
|
21
|
|
|
from st2common import log as logging |
22
|
|
|
from st2common.models.api.base import jsexpose |
23
|
|
|
from st2common.util.jsonify import json_encode |
24
|
|
|
from st2stream.listener import get_listener |
25
|
|
|
|
26
|
|
|
LOG = logging.getLogger(__name__) |
27
|
|
|
|
28
|
|
|
|
29
|
|
|
def format(gen): |
|
|
|
|
30
|
|
|
# Yield initial state so client would receive the headers the moment it connects to the stream |
31
|
|
|
yield '\n' |
32
|
|
|
|
33
|
|
|
message = '''event: %s\ndata: %s\n\n''' |
34
|
|
|
|
35
|
|
|
for pack in gen: |
36
|
|
|
if not pack: |
37
|
|
|
# Note: gunicorn wsgi handler expect bytes, not unicode |
38
|
|
|
yield six.binary_type('\n') |
39
|
|
|
else: |
40
|
|
|
(event, body) = pack |
41
|
|
|
# Note: gunicorn wsgi handler expect bytes, not unicode |
42
|
|
|
yield six.binary_type(message % (event, json_encode(body, indent=None))) |
43
|
|
|
|
44
|
|
|
|
45
|
|
|
class StreamController(RestController): |
46
|
|
|
@jsexpose(content_type='text/event-stream') |
47
|
|
|
def get_all(self): |
48
|
|
|
def make_response(): |
49
|
|
|
res = Response(content_type='text/event-stream', |
50
|
|
|
app_iter=format(get_listener().generator())) |
51
|
|
|
return res |
52
|
|
|
|
53
|
|
|
# Prohibit buffering response by eventlet |
54
|
|
|
pecan.request.environ['eventlet.minimum_write_chunk_size'] = 0 |
55
|
|
|
|
56
|
|
|
stream = make_response() |
57
|
|
|
|
58
|
|
|
return stream |
59
|
|
|
|
It is generally discouraged to redefine built-ins as this makes code very hard to read.