<commit_before># -*- coding: utf-8 -*-
# Copyright 2015 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from synapse.http.servlet import parse_integer, parse_string
from synapse.http.server import request_handler, finish_request
from synapse.replication.pusher_resource import PusherResource

from twisted.web.resource import Resource
from twisted.web.server import NOT_DONE_YET
from twisted.internet import defer

import ujson as json

import collections
import logging

logger = logging.getLogger(__name__)

REPLICATION_PREFIX = "/_synapse/replication"

STREAM_NAMES = (
    ("events",),
    ("presence",),
    ("typing",),
    ("receipts",),
    ("user_account_data", "room_account_data", "tag_account_data",),
    ("backfill",),
    ("push_rules",),
    ("pushers",),
    ("state",),
)


class ReplicationResource(Resource):
    """
    HTTP endpoint for extracting data from synapse.

    The streams of data returned by the endpoint are controlled by the
    parameters given to the API. To return a given stream pass a query
    parameter with a position in the stream to return data from or the
    special value "-1" to return data from the start of the stream.

    If there is no data for any of the supplied streams after the given
    position then the request will block until there is data for one
    of the streams. This allows clients to long-poll this API.

    The possible streams are:

    * "streams": A special stream returing the positions of other streams.
    * "events": The new events seen on the server.
    * "presence": Presence updates.
    * "typing": Typing updates.
    * "receipts": Receipt updates.
    * "user_account_data": Top-level per user account data.
    * "room_account_data: Per room per user account data.
    * "tag_account_data": Per room per user tags.
    * "backfill": Old events that have been backfilled from other servers.
    * "push_rules": Per user changes to push rules.
    * "pushers": Per user changes to their pushers.

    The API takes two additional query parameters:

    * "timeout": How long to wait before returning an empty response.
    * "limit": The maximum number of rows to return for the selected streams.

    The response is a JSON object with keys for each stream with updates. Under
    each key is a JSON object with:

    * "position": The current position of the stream.
    * "field_names": The names of the fields in each row.
    * "rows": The updates as an array of arrays.

    There are a number of ways this API could be used:

    1) To replicate the contents of the backing database to another database.
    2) To be notified when the contents of a shared backing database changes.
    3) To "tail" the activity happening on a server for debugging.

    In the first case the client would track all of the streams and store it's
    own copy of the data.

    In the second case the client might theoretically just be able to follow
    the "streams" stream to track where the other streams are. However in
    practise it will probably need to get the contents of the streams in
    order to expire the any in-memory caches. Whether it gets the contents
    of the streams from this replication API or directly from the backing
    store is a matter of taste.

    In the third case the client would use the "streams" stream to find what
    streams are available and their current positions. Then it can start
    long-polling this replication API for new data on those streams.
    """

    def __init__(self, hs):
        Resource.__init__(self)  # Resource is old-style, so no super()

        self.version_string = hs.version_string
        self.store = hs.get_datastore()
        self.sources = hs.get_event_sources()
        self.presence_handler = hs.get_handlers().presence_handler
        self.typing_handler = hs.get_handlers().typing_notification_handler
        self.notifier = hs.notifier
        self.clock = hs.get_clock()

        self.putChild("remove_pushers", PusherResource(hs))

    def render_GET(self, request):
        self._async_render_GET(request)
        return NOT_DONE_YET

    @defer.inlineCallbacks
    def current_replication_token(self):
        stream_token = yield self.sources.get_current_token()
        backfill_token = yield self.store.get_current_backfill_token()
        push_rules_token, room_stream_token = self.store.get_push_rules_stream_token()
        pushers_token = self.store.get_pushers_stream_token()
        state_token = self.store.get_state_stream_token()

        defer.returnValue(_ReplicationToken(
            room_stream_token,
            int(stream_token.presence_key),
            int(stream_token.typing_key),
            int(stream_token.receipt_key),
            int(stream_token.account_data_key),
            backfill_token,
            push_rules_token,
            pushers_token,
            state_token,
        ))

    @request_handler()
    @defer.inlineCallbacks
    def _async_render_GET(self, request):
        limit = parse_integer(request, "limit", 100)
        timeout = parse_integer(request, "timeout", 10 * 1000)

        request.setHeader(b"Content-Type", b"application/json")

        request_streams = {
            name: parse_integer(request, name)
            for names in STREAM_NAMES for name in names
        }
        request_streams["streams"] = parse_string(request, "streams")

        def replicate():
            return self.replicate(request_streams, limit)

        result = yield self.notifier.wait_for_replication(replicate, timeout)

        request.write(json.dumps(result, ensure_ascii=False))
        finish_request(request)<commit_msg>Add some log information at returned replication streams<commit_after># -*- coding: utf-8 -*-
# Copyright 2015 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from synapse.http.servlet import parse_integer, parse_string
from synapse.http.server import request_handler, finish_request
from synapse.replication.pusher_resource import PusherResource

from twisted.web.resource import Resource
from twisted.web.server import NOT_DONE_YET
from twisted.internet import defer

import ujson as json

import collections
import logging

logger = logging.getLogger(__name__)

REPLICATION_PREFIX = "/_synapse/replication"

STREAM_NAMES = (
    ("events",),
    ("presence",),
    ("typing",),
    ("receipts",),
    ("user_account_data", "room_account_data", "tag_account_data",),
    ("backfill",),
    ("push_rules",),
    ("pushers",),
    ("state",),
)


class ReplicationResource(Resource):
    """
    HTTP endpoint for extracting data from synapse.

    The streams of data returned by the endpoint are controlled by the
    parameters given to the API. To return a given stream pass a query
    parameter with a position in the stream to return data from or the
    special value "-1" to return data from the start of the stream.

    If there is no data for any of the supplied streams after the given
    position then the request will block until there is data for one
    of the streams. This allows clients to long-poll this API.

    The possible streams are:

    * "streams": A special stream returing the positions of other streams.
    * "events": The new events seen on the server.
    * "presence": Presence updates.
    * "typing": Typing updates.
    * "receipts": Receipt updates.
    * "user_account_data": Top-level per user account data.
    * "room_account_data: Per room per user account data.
    * "tag_account_data": Per room per user tags.
    * "backfill": Old events that have been backfilled from other servers.
    * "push_rules": Per user changes to push rules.
    * "pushers": Per user changes to their pushers.

    The API takes two additional query parameters:

    * "timeout": How long to wait before returning an empty response.
    * "limit": The maximum number of rows to return for the selected streams.

    The response is a JSON object with keys for each stream with updates. Under
    each key is a JSON object with:

    * "position": The current position of the stream.
    * "field_names": The names of the fields in each row.
    * "rows": The updates as an array of arrays.

    There are a number of ways this API could be used:

    1) To replicate the contents of the backing database to another database.
    2) To be notified when the contents of a shared backing database changes.
    3) To "tail" the activity happening on a server for debugging.

    In the first case the client would track all of the streams and store it's
    own copy of the data.

    In the second case the client might theoretically just be able to follow
    the "streams" stream to track where the other streams are. However in
    practise it will probably need to get the contents of the streams in
    order to expire the any in-memory caches. Whether it gets the contents
    of the streams from this replication API or directly from the backing
    store is a matter of taste.

    In the third case the client would use the "streams" stream to find what
    streams are available and their current positions. Then it can start
    long-polling this replication API for new data on those streams.
    """

    def __init__(self, hs):
        Resource.__init__(self)  # Resource is old-style, so no super()

        self.version_string = hs.version_string
        self.store = hs.get_datastore()
        self.sources = hs.get_event_sources()
        self.presence_handler = hs.get_handlers().presence_handler
        self.typing_handler = hs.get_handlers().typing_notification_handler
        self.notifier = hs.notifier
        self.clock = hs.get_clock()

        self.putChild("remove_pushers", PusherResource(hs))

    def render_GET(self, request):
        self._async_render_GET(request)
        return NOT_DONE_YET

    @defer.inlineCallbacks
    def current_replication_token(self):
        stream_token = yield self.sources.get_current_token()
        backfill_token = yield self.store.get_current_backfill_token()
        push_rules_token, room_stream_token = self.store.get_push_rules_stream_token()
        pushers_token = self.store.get_pushers_stream_token()
        state_token = self.store.get_state_stream_token()

        defer.returnValue(_ReplicationToken(
            room_stream_token,
            int(stream_token.presence_key),
            int(stream_token.typing_key),
            int(stream_token.receipt_key),
            int(stream_token.account_data_key),
            backfill_token,
            push_rules_token,
            pushers_token,
            state_token,
        ))

    @request_handler()
    @defer.inlineCallbacks
    def _async_render_GET(self, request):
        limit = parse_integer(request, "limit", 100)
        timeout = parse_integer(request, "timeout", 10 * 1000)

        request.setHeader(b"Content-Type", b"application/json")

        request_streams = {
            name: parse_integer(request, name)
            for names in STREAM_NAMES for name in names
        }
        request_streams["streams"] = parse_string(request, "streams")

        def replicate():
            return self.replicate(request_streams, limit)

        result = yield self.notifier.wait_for_replication(replicate, timeout)

        for stream_name, stream_content in result.items():
            logger.info(
                "Replicating %d rows of %s from %s -> %s",
                len(stream_content["rows"]),
                stream_name,
                stream_content["position"],
                request_streams.get(stream_name),
            )
            if stream_content["position"] == request_streams.get(stream_name):
                logger.warn("Returning same position for stream: %s", stream_name)

        request.write(json.dumps(result, ensure_ascii=False))
        finish_request(request)
{'fraction_non_alphanumeric': 0.07400482978889149, 'fraction_numerical': 0.003427592116538132, 'mean_word_length': 3.1042199488491047, 'pattern_counts': {'":': 30, '<': 3, '<?xml version=': 0, '>': 4, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5502749', 'n_tokens_mistral': 3546, 'n_tokens_neox': 3424, 'n_words': 1332}