We are trying to implement a system that look like this diagram:
In step 1, the User Application will call a Stored Procedure to call the service (begin the dialog conversation). And we need an ID to identify that request.
After that, the User Application will start making periodical request to the Reply "Queue" using Receive statement with Where clause (I put Queue in the double quote, because in fact it doesn't really work like a queue).
Here, the problem we have is that, how can we maintain a unique ID throughout the process (step 2 and 3), and that ID is somewhere outside of Message Body, because we want to use Where clause of Receive. The conversation_handle could not help us, because they are different from each endpoint.
Is there any ID that persist from the begin of the dialog until END CONVERSATION?
"Periodically ask for a response for a specific request"
You cannot do that. Your application must dequeue responses and handle them, as they become available, all of them. Any architecture that attempts to poll for specific messages will fail. This is a fundamental tenet of Service Broker.
Also you do not "ask periodically" in Service Broker. You have WAITFOR (RECEIVE ...) exactly to replace pooling 'periodically'.
We use this syntax:
BEGIN DIALOG CONVERSATION #Handle
FROM SERVICE #InitiatorService
TO SERVICE #TargetService
ON CONTRACT #OnContract
WITH ENCRYPTION = OFF;
The variable #Handle will after this statement contain a uniqueidentifier which will remain the same during the entire conversation. On the receiving end, we have this:
RECEIVE TOP(1)
#Handle = [conversation_handle],
#Type = [message_type_name],
#Message = [message_body]
FROM
[TargetQueue]
Which get the same value for #Handle as was created by the sender.
We have pretty much just implemented this: http://rusanu.com/2007/12/03/resending-messages/ and it works great.
Related
I created a small application (Spring Boot and camunda) to process an order process. The Order-Service receives the new order via Rest and calls the Start Event of the BPMN Order workflow. The order process contains two asynchronous JMS calls (Customer check and Warehouse Stock check). If both checks return the order process should continue.
The Start event is called within a Spring Rest Controller:
ProcessInstance processInstance =
runtimeService.startProcessInstanceByKey("orderService", String.valueOf(order.getId()));
The Send Task (e.g. the customer check) sends the JMS message into a asynchronous queue.
The answer of this service is catched by a another Spring component which then trys to send an intermediate message:
runtimeService.createMessageCorrelation("msgReceiveCheckCustomerCredibility")
.processInstanceBusinessKey(response.getOrder().getBpmnBusinessKey())
.setVariable("resultOrderCheckCustomterCredibility", response)
.correlate();
I deactivated the warehouse service to see if the order process waits for the arrival of the second call, but instead I get this exception:
1115 06:33:08.564 WARN [o.c.b.e.jobexecutor] ENGINE-14006 Exception while executing job 67d2cc24-0769-11ea-933a-d89ef3425300:
org.springframework.messaging.MessageHandlingException: nested exception is org.camunda.bpm.engine.MismatchingMessageCorrelationException: ENGINE-13031 Cannot correlate a message with name 'msgReceiveCheckCustomerCredibility' to a single execution. 4 executions match the correlation keys: CorrelationSet [businessKey=1, processInstanceId=null, processDefinitionId=null, correlationKeys=null, localCorrelationKeys=null, tenantId=null, isTenantIdSet=false]
This is my process. I cannot see a way to post my bpmn file :-(
What can't it not correlate with the message name and the business key? The JMS queues are empty, there are other messages with the same businessKey waiting.
Thanks!
Just to narrow the problem: Do a runtimeService eventSubscription query before you try to correlate and check what subscriptions are actually waiting .. maybe you have a duplicate message name? Maybe you (accidentally) have another instance of the same process running? Once you identified the subscriptions, you could just notify the execution directly without using the correlation builder ...
I am using the taskqueue API to send multiple emails is small groups with mailgun. My code looks more or less like this:
class CpMsg(ndb.Model):
group = ndb.KeyProperty()
sent = ndb.BooleanProperty()
#Other properties
def send_mail(messages):
"""Sends a request to mailgun's API"""
# Some code
pass
class MailTask(TaskHandler):
def post(self):
p_key = utils.key_from_string(self.request.get('p'))
msgs = CpMsg.query(
CpMsg.group==p_key,
CpMsg.sent==False).fetch(BATCH_SIZE)
if msgs:
send_mail(msgs)
for msg in msgs:
msg.sent = True
ndb.put_multi(msgs)
#Call the task again in COOLDOWN seconds
The code above has been working fine, but according to the docs, the taskqueue API guarantees that a task is delivered at least once, so tasks should be idempotent. Now, most of the time this would be the case with the above code, since it only gets messages that have the 'sent' property equal to False. The problem is that non ancestor ndb queries are only eventually consistent, which means that if the task is executed twice in quick succession the query may return stale results and include the messages that were just sent.
I thought of including an ancestor for the messages, but since the sent emails will be in the thousands I'm worried that may mean having large entity groups, which have a limited write throughput.
Should I use an ancestor to make the queries? Or maybe there is a way to configure mailgun to avoid sending the same email twice? Should I just accept the risk that in some rare cases a few emails may be sent more than once?
One possible approach to avoid the eventual consistency hurdle is to make the query a keys_only one, then iterate through the message keys to get the actual messages by key lookup (strong consistency), check if msg.sent is True and skip sending those messages in such case. Something along these lines:
msg_keys = CpMsg.query(
CpMsg.group==p_key,
CpMsg.sent==False).fetch(BATCH_SIZE, keys_only=True)
if not msg_keys:
return
msgs = ndb.get_multi(msg_keys)
msgs_to_send = []
for msg in msgs:
if not msg.sent:
msgs_to_send.append(msg)
if msgs_to_send:
send_mail(msgs_to_send)
for msg in msgs_to_send:
msg.sent = True
ndb.put_multi(msgs_to_send)
You'd also have to make your post call transactional (with the #ndb.transactional() decorator).
This should address the duplicates caused by the query eventual consistency. However there still is room for duplicates caused by transaction retries due to datastore contention (or any other reason) - as the send_mail() call isn't idempotent. Sending one message at a time (maybe using the task queue) could reduce the chance of that happening. See also GAE/P: Transaction safety with API calls
I have a telegram bot that for any received message runs a program in the server and sends its result back. But there is a problem! If a user sends too many messages to my bot(spamming), it will make server so busy!
Is there any way to block the people whom send more than 5 messages in a second and don't receive their messages anymore? (using telegram api!!)
Firstly I have to say that Telegram Bot API does not have such a capability itself, Therefore you will need to implement it on your own and all you need to do is:
Count the number of the messages that a user sends within a second which won't be so easy without having a database. But if you have a database with a table called Black_List and save all the messages with their sent-time in another table, you'll be able to count the number of messages sent via one specific ChatID in a pre-defined time period(In your case; 1 second) and check if the count is bigger than 5 or not, if the answer was YES you can insert that ChatID to the Black_List table.
Every time the bot receives a message it must run a database query to see that the sender's chatID exists in the Black_List table or not. If it exists it should continue its own job and ignore the message(Or even it can send an alert to the user saying: "You're blocked." which I think can be time consuming).
Note that as I know the current telegram bot API doesn't have the feature to stop receiving messages but as I mentioned above you can ignore the messages from spammers.
In order to save time, You should avoid making a database connection
every time the bot receives an update(message), instead you can load
the ChatIDs that exist in the Black_List to a DataSet and update the
DataSet right after the insertion of a new spammer ChatID to the
Black_List table. This way the number of the queries will reduce
noticeably.
I have achieved it by this mean:
# Using the ttlcache to set a time-limited dict. you can adjust the ttl.
ttl_cache = cachetools.TTLCache(maxsize=128, ttl=60)
def check_user_msg_frequency(message):
print(ttl_cache)
msg_cnt = ttl_cache[message.from_user.id]
if msg_cnt > 3:
now = datetime.now()
until = now + timedelta(seconds=60*10)
bot.restrict_chat_member(message.chat.id, message.from_user.id, until_date=until)
def set_user_msg_frequency(message):
if not ttl_cache.get(message.from_user.id):
ttl_cache[message.from_user.id] = 1
else:
ttl_cache[message.from_user.id] += 1
With these to functions above, you can record how many messages sent by any user in the period. If a user's messages sent more than expected, he would be restricted.
Then, every handler you called should call these two functions:
#bot.message_handler(commands=['start', 'help'])
def handle_start_help(message):
set_user_msg_frequency(message)
check_user_msg_frequency(message)
I'm using pyTelegramBotAPI this module to handle.
I know I'm late to the party, but here is another simple solution that doesn't use a Db:
Create a ConversationState class to attach to each telegram Id when they start to chat with the bot
Then add a LastMessage DateTime variable to the ConversationState class
Now every time you receive a message check if enought time has passed from the LasteMessage DateTime, if not enought time has passed answer with a warning message.
You can also implement a timer that deletes the conversation state class if you are worried about performance.
I'm trying to learn the basics of Service Broker, and have created an application originally based on the SSMS template. However I can't send a message to my queue. It just says the message type is not part of the service contract.
The absolute bare minimum I need to recreate this is the following batch:
USE [test_db]
GO
CREATE MESSAGE TYPE [test_message]
AUTHORIZATION [dbo]
VALIDATION = WELL_FORMED_XML
GO
CREATE CONTRACT [test_contract]
AUTHORIZATION [dbo] (
[test_message] SENT BY ANY
)
GO
CREATE QUEUE [dbo].[test_queue]
WITH STATUS = ON
,RETENTION = OFF
--,ACTIVATION (
-- STATUS = ON
-- ,PROCEDURE_NAME = [dbo].[test_activator]
-- ,MAX_QUEUE_READERS = 1
-- ,EXECUTE AS N'dbo'
--)
ON [PRIMARY]
GO
CREATE SERVICE [test_service]
AUTHORIZATION [dbo]
ON QUEUE [dbo].[test_queue] (
[test_contract]
)
GO
BEGIN TRANSACTION
DECLARE #dialog_handle UNIQUEIDENTIFIER
BEGIN DIALOG #dialog_handle
FROM SERVICE test_service
TO SERVICE N'test_service';
SEND ON CONVERSATION #dialog_handle
MESSAGE TYPE test_message (N'<test />');
END CONVERSATION #dialog_handle;
COMMIT TRANSACTION
GO
...which yields:
Msg 8431, Level 16, State 1, Line 10
The message type 'test_message' is not part of the service contract.
I only need to be able to send asynchronous messages within the same database. There are no remote connections to consider, and I don't strictly even need to handle a reply.
I've checked and double-checked that the message type, contract, queue and service all exist and the properties of the contract says that the message type is included
What am I missing?
As Denis already answered, you're missing the ON CONTRACT test_contract.
If you omit it then the DEFAULT contract is used. Every database has a contract named DEFAULT which has one message type, also named DEFAULT. The DEFAULT contract is used when you omit any contract in BEGIN DIALOG and the DEFAULT message type is used when you omit the message type in SEND:
BEGIN DIALOG #dialog_handle
FROM SERVICE test_service
TO SERVICE N'test_service'; <-- will use the DEFAULT contract
SEND ON CONVERSATION #dialog_handle
(N'<test />'); <-- will use the DEFAULT message type
DEFAULT message type has no validation. The DEFAULT contract binds the DEFAULT message type to both initiator and target (both can send the message in this contract, ie. SENT BY ANY). Contract and message type names are always case sensitive, irrelevant of database collation, so the name DEFAULT is case sensitive.
Try this:
BEGIN DIALOG #dialog_handle
FROM SERVICE test_service
TO SERVICE N'test_service'
ON CONTRACT test_contract;
Let say I have two instances of the same app interacting with a backend service in Service Broker. How can each instance know to handle only conversations it initiated and ignore the rest? If I recall correctly, every RECEIVE will remove the message from the queue.
Here's an example:
-- Assume the SquareService return the square of the number sent to it
-- Instance 1
BEGIN DIALOG #Conversation1
FROM SERVICE InitService
TO SERVICE 'SquareService'
ON CONTRACT (MyContract)
WITH ENCRYPTION = OFF;
SEND ON CONVERSATION #Conversation1 MESSAGE TYPE MyMessageType('1');
-- Instance 2
BEGIN DIALOG #Conversation2
...;
SEND ON CONVERSATION #Conversation2 MESSAGE TYPE MyMessageType('2');
Now who should I write the RECEIVE statement so that Instance 1 will correctly get 1 and Instance 2 get 4 back?
You are already using a Conversation Group.
Is this not sufficient for your needs when Receiving the messages?
-> using GET CONVERSATION GROUP and RECEIVE together
you can read more about it here: http://technet.microsoft.com/en-us/library/ms166131%28v=sql.105%29.aspx
and also here Sql Server Service Broker Conversation Groups
I'm assuming you have an InitQueue associated with your InitService. You can use a WHERE clause with RECEIVE to listen for messages on the same conversation:
WAITFOR (RECEIVE #response = CONVERT(xml, message_body)
FROM InitQueue -- InitService setup to use InitQueue?
WHERE conversation_handle = #Conversation1