You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

543 lines
15 KiB

rpc/lib/client & server: try to conform to JSON-RPC 2.0 spec (#4141) https://www.jsonrpc.org/specification What is done in this PR: JSONRPCClient: validate that Response.ID matches Request.ID I wanted to do the same for the WSClient, but since we're sending events as responses, not notifications, checking IDs would require storing them in memory indefinitely (and we won't be able to remove them upon client unsubscribing because ID is different then). Request.ID is now optional. Notification is a Request without an ID. Previously "" or 0 were considered as notifications Remove #event suffix from ID from an event response (partially fixes #2949) ID must be either string, int or null AND must be equal to request's ID. Now, because we've implemented events as responses, WS clients are tripping when they see Response.ID("0#event") != Request.ID("0"). Implementing events as requests would require a lot of time (~ 2 days to completely rewrite WS client and server) generate unique ID for each request switch to integer IDs instead of "json-client-XYZ" id=0 method=/subscribe id=0 result=... id=1 method=/abci_query id=1 result=... > send events (resulting from /subscribe) as requests+notifications (not responses) this will require a lot of work. probably not worth it * rpc: generate an unique ID for each request in conformance with JSON-RPC spec * WSClient: check for unsolicited responses * fix golangci warnings * save commit * fix errors * remove ID from responses from subscribe Refs #2949 * clients are safe for concurrent access * tm-bench: switch to int ID * fixes after my own review * comment out sentIDs in WSClient see commit body for the reason * remove body.Close it will be closed automatically * stop ws connection outside of write/read routines also, use t.Rate in tm-bench indexer when calculating ID fix gocritic issues * update swagger.yaml * Apply suggestions from code review * fix stylecheck and golint linter warnings * update changelog * update changelog2
5 years ago
rpc/lib/client & server: try to conform to JSON-RPC 2.0 spec (#4141) https://www.jsonrpc.org/specification What is done in this PR: JSONRPCClient: validate that Response.ID matches Request.ID I wanted to do the same for the WSClient, but since we're sending events as responses, not notifications, checking IDs would require storing them in memory indefinitely (and we won't be able to remove them upon client unsubscribing because ID is different then). Request.ID is now optional. Notification is a Request without an ID. Previously "" or 0 were considered as notifications Remove #event suffix from ID from an event response (partially fixes #2949) ID must be either string, int or null AND must be equal to request's ID. Now, because we've implemented events as responses, WS clients are tripping when they see Response.ID("0#event") != Request.ID("0"). Implementing events as requests would require a lot of time (~ 2 days to completely rewrite WS client and server) generate unique ID for each request switch to integer IDs instead of "json-client-XYZ" id=0 method=/subscribe id=0 result=... id=1 method=/abci_query id=1 result=... > send events (resulting from /subscribe) as requests+notifications (not responses) this will require a lot of work. probably not worth it * rpc: generate an unique ID for each request in conformance with JSON-RPC spec * WSClient: check for unsolicited responses * fix golangci warnings * save commit * fix errors * remove ID from responses from subscribe Refs #2949 * clients are safe for concurrent access * tm-bench: switch to int ID * fixes after my own review * comment out sentIDs in WSClient see commit body for the reason * remove body.Close it will be closed automatically * stop ws connection outside of write/read routines also, use t.Rate in tm-bench indexer when calculating ID fix gocritic issues * update swagger.yaml * Apply suggestions from code review * fix stylecheck and golint linter warnings * update changelog * update changelog2
5 years ago
rpc/lib/client & server: try to conform to JSON-RPC 2.0 spec (#4141) https://www.jsonrpc.org/specification What is done in this PR: JSONRPCClient: validate that Response.ID matches Request.ID I wanted to do the same for the WSClient, but since we're sending events as responses, not notifications, checking IDs would require storing them in memory indefinitely (and we won't be able to remove them upon client unsubscribing because ID is different then). Request.ID is now optional. Notification is a Request without an ID. Previously "" or 0 were considered as notifications Remove #event suffix from ID from an event response (partially fixes #2949) ID must be either string, int or null AND must be equal to request's ID. Now, because we've implemented events as responses, WS clients are tripping when they see Response.ID("0#event") != Request.ID("0"). Implementing events as requests would require a lot of time (~ 2 days to completely rewrite WS client and server) generate unique ID for each request switch to integer IDs instead of "json-client-XYZ" id=0 method=/subscribe id=0 result=... id=1 method=/abci_query id=1 result=... > send events (resulting from /subscribe) as requests+notifications (not responses) this will require a lot of work. probably not worth it * rpc: generate an unique ID for each request in conformance with JSON-RPC spec * WSClient: check for unsolicited responses * fix golangci warnings * save commit * fix errors * remove ID from responses from subscribe Refs #2949 * clients are safe for concurrent access * tm-bench: switch to int ID * fixes after my own review * comment out sentIDs in WSClient see commit body for the reason * remove body.Close it will be closed automatically * stop ws connection outside of write/read routines also, use t.Rate in tm-bench indexer when calculating ID fix gocritic issues * update swagger.yaml * Apply suggestions from code review * fix stylecheck and golint linter warnings * update changelog * update changelog2
5 years ago
rpc/lib/client & server: try to conform to JSON-RPC 2.0 spec (#4141) https://www.jsonrpc.org/specification What is done in this PR: JSONRPCClient: validate that Response.ID matches Request.ID I wanted to do the same for the WSClient, but since we're sending events as responses, not notifications, checking IDs would require storing them in memory indefinitely (and we won't be able to remove them upon client unsubscribing because ID is different then). Request.ID is now optional. Notification is a Request without an ID. Previously "" or 0 were considered as notifications Remove #event suffix from ID from an event response (partially fixes #2949) ID must be either string, int or null AND must be equal to request's ID. Now, because we've implemented events as responses, WS clients are tripping when they see Response.ID("0#event") != Request.ID("0"). Implementing events as requests would require a lot of time (~ 2 days to completely rewrite WS client and server) generate unique ID for each request switch to integer IDs instead of "json-client-XYZ" id=0 method=/subscribe id=0 result=... id=1 method=/abci_query id=1 result=... > send events (resulting from /subscribe) as requests+notifications (not responses) this will require a lot of work. probably not worth it * rpc: generate an unique ID for each request in conformance with JSON-RPC spec * WSClient: check for unsolicited responses * fix golangci warnings * save commit * fix errors * remove ID from responses from subscribe Refs #2949 * clients are safe for concurrent access * tm-bench: switch to int ID * fixes after my own review * comment out sentIDs in WSClient see commit body for the reason * remove body.Close it will be closed automatically * stop ws connection outside of write/read routines also, use t.Rate in tm-bench indexer when calculating ID fix gocritic issues * update swagger.yaml * Apply suggestions from code review * fix stylecheck and golint linter warnings * update changelog * update changelog2
5 years ago
7 years ago
7 years ago
7 years ago
7 years ago
rpc/lib/client & server: try to conform to JSON-RPC 2.0 spec (#4141) https://www.jsonrpc.org/specification What is done in this PR: JSONRPCClient: validate that Response.ID matches Request.ID I wanted to do the same for the WSClient, but since we're sending events as responses, not notifications, checking IDs would require storing them in memory indefinitely (and we won't be able to remove them upon client unsubscribing because ID is different then). Request.ID is now optional. Notification is a Request without an ID. Previously "" or 0 were considered as notifications Remove #event suffix from ID from an event response (partially fixes #2949) ID must be either string, int or null AND must be equal to request's ID. Now, because we've implemented events as responses, WS clients are tripping when they see Response.ID("0#event") != Request.ID("0"). Implementing events as requests would require a lot of time (~ 2 days to completely rewrite WS client and server) generate unique ID for each request switch to integer IDs instead of "json-client-XYZ" id=0 method=/subscribe id=0 result=... id=1 method=/abci_query id=1 result=... > send events (resulting from /subscribe) as requests+notifications (not responses) this will require a lot of work. probably not worth it * rpc: generate an unique ID for each request in conformance with JSON-RPC spec * WSClient: check for unsolicited responses * fix golangci warnings * save commit * fix errors * remove ID from responses from subscribe Refs #2949 * clients are safe for concurrent access * tm-bench: switch to int ID * fixes after my own review * comment out sentIDs in WSClient see commit body for the reason * remove body.Close it will be closed automatically * stop ws connection outside of write/read routines also, use t.Rate in tm-bench indexer when calculating ID fix gocritic issues * update swagger.yaml * Apply suggestions from code review * fix stylecheck and golint linter warnings * update changelog * update changelog2
5 years ago
rpc/lib/client & server: try to conform to JSON-RPC 2.0 spec (#4141) https://www.jsonrpc.org/specification What is done in this PR: JSONRPCClient: validate that Response.ID matches Request.ID I wanted to do the same for the WSClient, but since we're sending events as responses, not notifications, checking IDs would require storing them in memory indefinitely (and we won't be able to remove them upon client unsubscribing because ID is different then). Request.ID is now optional. Notification is a Request without an ID. Previously "" or 0 were considered as notifications Remove #event suffix from ID from an event response (partially fixes #2949) ID must be either string, int or null AND must be equal to request's ID. Now, because we've implemented events as responses, WS clients are tripping when they see Response.ID("0#event") != Request.ID("0"). Implementing events as requests would require a lot of time (~ 2 days to completely rewrite WS client and server) generate unique ID for each request switch to integer IDs instead of "json-client-XYZ" id=0 method=/subscribe id=0 result=... id=1 method=/abci_query id=1 result=... > send events (resulting from /subscribe) as requests+notifications (not responses) this will require a lot of work. probably not worth it * rpc: generate an unique ID for each request in conformance with JSON-RPC spec * WSClient: check for unsolicited responses * fix golangci warnings * save commit * fix errors * remove ID from responses from subscribe Refs #2949 * clients are safe for concurrent access * tm-bench: switch to int ID * fixes after my own review * comment out sentIDs in WSClient see commit body for the reason * remove body.Close it will be closed automatically * stop ws connection outside of write/read routines also, use t.Rate in tm-bench indexer when calculating ID fix gocritic issues * update swagger.yaml * Apply suggestions from code review * fix stylecheck and golint linter warnings * update changelog * update changelog2
5 years ago
rpc/lib/client & server: try to conform to JSON-RPC 2.0 spec (#4141) https://www.jsonrpc.org/specification What is done in this PR: JSONRPCClient: validate that Response.ID matches Request.ID I wanted to do the same for the WSClient, but since we're sending events as responses, not notifications, checking IDs would require storing them in memory indefinitely (and we won't be able to remove them upon client unsubscribing because ID is different then). Request.ID is now optional. Notification is a Request without an ID. Previously "" or 0 were considered as notifications Remove #event suffix from ID from an event response (partially fixes #2949) ID must be either string, int or null AND must be equal to request's ID. Now, because we've implemented events as responses, WS clients are tripping when they see Response.ID("0#event") != Request.ID("0"). Implementing events as requests would require a lot of time (~ 2 days to completely rewrite WS client and server) generate unique ID for each request switch to integer IDs instead of "json-client-XYZ" id=0 method=/subscribe id=0 result=... id=1 method=/abci_query id=1 result=... > send events (resulting from /subscribe) as requests+notifications (not responses) this will require a lot of work. probably not worth it * rpc: generate an unique ID for each request in conformance with JSON-RPC spec * WSClient: check for unsolicited responses * fix golangci warnings * save commit * fix errors * remove ID from responses from subscribe Refs #2949 * clients are safe for concurrent access * tm-bench: switch to int ID * fixes after my own review * comment out sentIDs in WSClient see commit body for the reason * remove body.Close it will be closed automatically * stop ws connection outside of write/read routines also, use t.Rate in tm-bench indexer when calculating ID fix gocritic issues * update swagger.yaml * Apply suggestions from code review * fix stylecheck and golint linter warnings * update changelog * update changelog2
5 years ago
rpc/lib/client & server: try to conform to JSON-RPC 2.0 spec (#4141) https://www.jsonrpc.org/specification What is done in this PR: JSONRPCClient: validate that Response.ID matches Request.ID I wanted to do the same for the WSClient, but since we're sending events as responses, not notifications, checking IDs would require storing them in memory indefinitely (and we won't be able to remove them upon client unsubscribing because ID is different then). Request.ID is now optional. Notification is a Request without an ID. Previously "" or 0 were considered as notifications Remove #event suffix from ID from an event response (partially fixes #2949) ID must be either string, int or null AND must be equal to request's ID. Now, because we've implemented events as responses, WS clients are tripping when they see Response.ID("0#event") != Request.ID("0"). Implementing events as requests would require a lot of time (~ 2 days to completely rewrite WS client and server) generate unique ID for each request switch to integer IDs instead of "json-client-XYZ" id=0 method=/subscribe id=0 result=... id=1 method=/abci_query id=1 result=... > send events (resulting from /subscribe) as requests+notifications (not responses) this will require a lot of work. probably not worth it * rpc: generate an unique ID for each request in conformance with JSON-RPC spec * WSClient: check for unsolicited responses * fix golangci warnings * save commit * fix errors * remove ID from responses from subscribe Refs #2949 * clients are safe for concurrent access * tm-bench: switch to int ID * fixes after my own review * comment out sentIDs in WSClient see commit body for the reason * remove body.Close it will be closed automatically * stop ws connection outside of write/read routines also, use t.Rate in tm-bench indexer when calculating ID fix gocritic issues * update swagger.yaml * Apply suggestions from code review * fix stylecheck and golint linter warnings * update changelog * update changelog2
5 years ago
rpc/lib/client & server: try to conform to JSON-RPC 2.0 spec (#4141) https://www.jsonrpc.org/specification What is done in this PR: JSONRPCClient: validate that Response.ID matches Request.ID I wanted to do the same for the WSClient, but since we're sending events as responses, not notifications, checking IDs would require storing them in memory indefinitely (and we won't be able to remove them upon client unsubscribing because ID is different then). Request.ID is now optional. Notification is a Request without an ID. Previously "" or 0 were considered as notifications Remove #event suffix from ID from an event response (partially fixes #2949) ID must be either string, int or null AND must be equal to request's ID. Now, because we've implemented events as responses, WS clients are tripping when they see Response.ID("0#event") != Request.ID("0"). Implementing events as requests would require a lot of time (~ 2 days to completely rewrite WS client and server) generate unique ID for each request switch to integer IDs instead of "json-client-XYZ" id=0 method=/subscribe id=0 result=... id=1 method=/abci_query id=1 result=... > send events (resulting from /subscribe) as requests+notifications (not responses) this will require a lot of work. probably not worth it * rpc: generate an unique ID for each request in conformance with JSON-RPC spec * WSClient: check for unsolicited responses * fix golangci warnings * save commit * fix errors * remove ID from responses from subscribe Refs #2949 * clients are safe for concurrent access * tm-bench: switch to int ID * fixes after my own review * comment out sentIDs in WSClient see commit body for the reason * remove body.Close it will be closed automatically * stop ws connection outside of write/read routines also, use t.Rate in tm-bench indexer when calculating ID fix gocritic issues * update swagger.yaml * Apply suggestions from code review * fix stylecheck and golint linter warnings * update changelog * update changelog2
5 years ago
rpc/lib/client & server: try to conform to JSON-RPC 2.0 spec (#4141) https://www.jsonrpc.org/specification What is done in this PR: JSONRPCClient: validate that Response.ID matches Request.ID I wanted to do the same for the WSClient, but since we're sending events as responses, not notifications, checking IDs would require storing them in memory indefinitely (and we won't be able to remove them upon client unsubscribing because ID is different then). Request.ID is now optional. Notification is a Request without an ID. Previously "" or 0 were considered as notifications Remove #event suffix from ID from an event response (partially fixes #2949) ID must be either string, int or null AND must be equal to request's ID. Now, because we've implemented events as responses, WS clients are tripping when they see Response.ID("0#event") != Request.ID("0"). Implementing events as requests would require a lot of time (~ 2 days to completely rewrite WS client and server) generate unique ID for each request switch to integer IDs instead of "json-client-XYZ" id=0 method=/subscribe id=0 result=... id=1 method=/abci_query id=1 result=... > send events (resulting from /subscribe) as requests+notifications (not responses) this will require a lot of work. probably not worth it * rpc: generate an unique ID for each request in conformance with JSON-RPC spec * WSClient: check for unsolicited responses * fix golangci warnings * save commit * fix errors * remove ID from responses from subscribe Refs #2949 * clients are safe for concurrent access * tm-bench: switch to int ID * fixes after my own review * comment out sentIDs in WSClient see commit body for the reason * remove body.Close it will be closed automatically * stop ws connection outside of write/read routines also, use t.Rate in tm-bench indexer when calculating ID fix gocritic issues * update swagger.yaml * Apply suggestions from code review * fix stylecheck and golint linter warnings * update changelog * update changelog2
5 years ago
rpc/lib/client & server: try to conform to JSON-RPC 2.0 spec (#4141) https://www.jsonrpc.org/specification What is done in this PR: JSONRPCClient: validate that Response.ID matches Request.ID I wanted to do the same for the WSClient, but since we're sending events as responses, not notifications, checking IDs would require storing them in memory indefinitely (and we won't be able to remove them upon client unsubscribing because ID is different then). Request.ID is now optional. Notification is a Request without an ID. Previously "" or 0 were considered as notifications Remove #event suffix from ID from an event response (partially fixes #2949) ID must be either string, int or null AND must be equal to request's ID. Now, because we've implemented events as responses, WS clients are tripping when they see Response.ID("0#event") != Request.ID("0"). Implementing events as requests would require a lot of time (~ 2 days to completely rewrite WS client and server) generate unique ID for each request switch to integer IDs instead of "json-client-XYZ" id=0 method=/subscribe id=0 result=... id=1 method=/abci_query id=1 result=... > send events (resulting from /subscribe) as requests+notifications (not responses) this will require a lot of work. probably not worth it * rpc: generate an unique ID for each request in conformance with JSON-RPC spec * WSClient: check for unsolicited responses * fix golangci warnings * save commit * fix errors * remove ID from responses from subscribe Refs #2949 * clients are safe for concurrent access * tm-bench: switch to int ID * fixes after my own review * comment out sentIDs in WSClient see commit body for the reason * remove body.Close it will be closed automatically * stop ws connection outside of write/read routines also, use t.Rate in tm-bench indexer when calculating ID fix gocritic issues * update swagger.yaml * Apply suggestions from code review * fix stylecheck and golint linter warnings * update changelog * update changelog2
5 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
8 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
8 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
8 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
8 years ago
  1. package client
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "net"
  7. "net/http"
  8. "sync"
  9. "time"
  10. "github.com/gorilla/websocket"
  11. metrics "github.com/rcrowley/go-metrics"
  12. tmrand "github.com/tendermint/tendermint/libs/rand"
  13. "github.com/tendermint/tendermint/libs/service"
  14. tmsync "github.com/tendermint/tendermint/libs/sync"
  15. types "github.com/tendermint/tendermint/rpc/jsonrpc/types"
  16. )
  17. const (
  18. defaultMaxReconnectAttempts = 25
  19. defaultWriteWait = 0
  20. defaultReadWait = 0
  21. defaultPingPeriod = 0
  22. )
  23. // WSClient is a JSON-RPC client, which uses WebSocket for communication with
  24. // the remote server.
  25. //
  26. // WSClient is safe for concurrent use by multiple goroutines.
  27. type WSClient struct { // nolint: maligned
  28. conn *websocket.Conn
  29. Address string // IP:PORT or /path/to/socket
  30. Endpoint string // /websocket/url/endpoint
  31. Dialer func(string, string) (net.Conn, error)
  32. // Single user facing channel to read RPCResponses from, closed only when the
  33. // client is being stopped.
  34. ResponsesCh chan types.RPCResponse
  35. // Callback, which will be called each time after successful reconnect.
  36. onReconnect func()
  37. // internal channels
  38. send chan types.RPCRequest // user requests
  39. backlog chan types.RPCRequest // stores a single user request received during a conn failure
  40. reconnectAfter chan error // reconnect requests
  41. readRoutineQuit chan struct{} // a way for readRoutine to close writeRoutine
  42. // Maximum reconnect attempts (0 or greater; default: 25).
  43. maxReconnectAttempts int
  44. // Support both ws and wss protocols
  45. protocol string
  46. wg sync.WaitGroup
  47. mtx tmsync.RWMutex
  48. sentLastPingAt time.Time
  49. reconnecting bool
  50. nextReqID int
  51. // sentIDs map[types.JSONRPCIntID]bool // IDs of the requests currently in flight
  52. // Time allowed to write a message to the server. 0 means block until operation succeeds.
  53. writeWait time.Duration
  54. // Time allowed to read the next message from the server. 0 means block until operation succeeds.
  55. readWait time.Duration
  56. // Send pings to server with this period. Must be less than readWait. If 0, no pings will be sent.
  57. pingPeriod time.Duration
  58. service.BaseService
  59. // Time between sending a ping and receiving a pong. See
  60. // https://godoc.org/github.com/rcrowley/go-metrics#Timer.
  61. PingPongLatencyTimer metrics.Timer
  62. }
  63. // NewWS returns a new client. See the commentary on the func(*WSClient)
  64. // functions for a detailed description of how to configure ping period and
  65. // pong wait time. The endpoint argument must begin with a `/`.
  66. // An error is returned on invalid remote. The function panics when remote is nil.
  67. func NewWS(remoteAddr, endpoint string, options ...func(*WSClient)) (*WSClient, error) {
  68. parsedURL, err := newParsedURL(remoteAddr)
  69. if err != nil {
  70. return nil, err
  71. }
  72. // default to ws protocol, unless wss is explicitly specified
  73. if parsedURL.Scheme != protoWSS {
  74. parsedURL.Scheme = protoWS
  75. }
  76. dialFn, err := makeHTTPDialer(remoteAddr)
  77. if err != nil {
  78. return nil, err
  79. }
  80. c := &WSClient{
  81. Address: parsedURL.GetTrimmedHostWithPath(),
  82. Dialer: dialFn,
  83. Endpoint: endpoint,
  84. PingPongLatencyTimer: metrics.NewTimer(),
  85. maxReconnectAttempts: defaultMaxReconnectAttempts,
  86. readWait: defaultReadWait,
  87. writeWait: defaultWriteWait,
  88. pingPeriod: defaultPingPeriod,
  89. protocol: parsedURL.Scheme,
  90. // sentIDs: make(map[types.JSONRPCIntID]bool),
  91. }
  92. c.BaseService = *service.NewBaseService(nil, "WSClient", c)
  93. for _, option := range options {
  94. option(c)
  95. }
  96. return c, nil
  97. }
  98. // MaxReconnectAttempts sets the maximum number of reconnect attempts before returning an error.
  99. // It should only be used in the constructor and is not Goroutine-safe.
  100. func MaxReconnectAttempts(max int) func(*WSClient) {
  101. return func(c *WSClient) {
  102. c.maxReconnectAttempts = max
  103. }
  104. }
  105. // ReadWait sets the amount of time to wait before a websocket read times out.
  106. // It should only be used in the constructor and is not Goroutine-safe.
  107. func ReadWait(readWait time.Duration) func(*WSClient) {
  108. return func(c *WSClient) {
  109. c.readWait = readWait
  110. }
  111. }
  112. // WriteWait sets the amount of time to wait before a websocket write times out.
  113. // It should only be used in the constructor and is not Goroutine-safe.
  114. func WriteWait(writeWait time.Duration) func(*WSClient) {
  115. return func(c *WSClient) {
  116. c.writeWait = writeWait
  117. }
  118. }
  119. // PingPeriod sets the duration for sending websocket pings.
  120. // It should only be used in the constructor - not Goroutine-safe.
  121. func PingPeriod(pingPeriod time.Duration) func(*WSClient) {
  122. return func(c *WSClient) {
  123. c.pingPeriod = pingPeriod
  124. }
  125. }
  126. // OnReconnect sets the callback, which will be called every time after
  127. // successful reconnect.
  128. func OnReconnect(cb func()) func(*WSClient) {
  129. return func(c *WSClient) {
  130. c.onReconnect = cb
  131. }
  132. }
  133. // String returns WS client full address.
  134. func (c *WSClient) String() string {
  135. return fmt.Sprintf("WSClient{%s (%s)}", c.Address, c.Endpoint)
  136. }
  137. // OnStart implements service.Service by dialing a server and creating read and
  138. // write routines.
  139. func (c *WSClient) OnStart() error {
  140. err := c.dial()
  141. if err != nil {
  142. return err
  143. }
  144. c.ResponsesCh = make(chan types.RPCResponse)
  145. c.send = make(chan types.RPCRequest)
  146. // 1 additional error may come from the read/write
  147. // goroutine depending on which failed first.
  148. c.reconnectAfter = make(chan error, 1)
  149. // capacity for 1 request. a user won't be able to send more because the send
  150. // channel is unbuffered.
  151. c.backlog = make(chan types.RPCRequest, 1)
  152. c.startReadWriteRoutines()
  153. go c.reconnectRoutine()
  154. return nil
  155. }
  156. // Stop overrides service.Service#Stop. There is no other way to wait until Quit
  157. // channel is closed.
  158. func (c *WSClient) Stop() error {
  159. if err := c.BaseService.Stop(); err != nil {
  160. return err
  161. }
  162. // only close user-facing channels when we can't write to them
  163. c.wg.Wait()
  164. close(c.ResponsesCh)
  165. return nil
  166. }
  167. // IsReconnecting returns true if the client is reconnecting right now.
  168. func (c *WSClient) IsReconnecting() bool {
  169. c.mtx.RLock()
  170. defer c.mtx.RUnlock()
  171. return c.reconnecting
  172. }
  173. // IsActive returns true if the client is running and not reconnecting.
  174. func (c *WSClient) IsActive() bool {
  175. return c.IsRunning() && !c.IsReconnecting()
  176. }
  177. // Send the given RPC request to the server. Results will be available on
  178. // ResponsesCh, errors, if any, on ErrorsCh. Will block until send succeeds or
  179. // ctx.Done is closed.
  180. func (c *WSClient) Send(ctx context.Context, request types.RPCRequest) error {
  181. select {
  182. case c.send <- request:
  183. c.Logger.Info("sent a request", "req", request)
  184. // c.mtx.Lock()
  185. // c.sentIDs[request.ID.(types.JSONRPCIntID)] = true
  186. // c.mtx.Unlock()
  187. return nil
  188. case <-ctx.Done():
  189. return ctx.Err()
  190. }
  191. }
  192. // Call enqueues a call request onto the Send queue. Requests are JSON encoded.
  193. func (c *WSClient) Call(ctx context.Context, method string, params map[string]interface{}) error {
  194. request, err := types.MapToRequest(c.nextRequestID(), method, params)
  195. if err != nil {
  196. return err
  197. }
  198. return c.Send(ctx, request)
  199. }
  200. // CallWithArrayParams enqueues a call request onto the Send queue. Params are
  201. // in a form of array (e.g. []interface{}{"abcd"}). Requests are JSON encoded.
  202. func (c *WSClient) CallWithArrayParams(ctx context.Context, method string, params []interface{}) error {
  203. request, err := types.ArrayToRequest(c.nextRequestID(), method, params)
  204. if err != nil {
  205. return err
  206. }
  207. return c.Send(ctx, request)
  208. }
  209. ///////////////////////////////////////////////////////////////////////////////
  210. // Private methods
  211. func (c *WSClient) nextRequestID() types.JSONRPCIntID {
  212. c.mtx.Lock()
  213. id := c.nextReqID
  214. c.nextReqID++
  215. c.mtx.Unlock()
  216. return types.JSONRPCIntID(id)
  217. }
  218. func (c *WSClient) dial() error {
  219. dialer := &websocket.Dialer{
  220. NetDial: c.Dialer,
  221. Proxy: http.ProxyFromEnvironment,
  222. }
  223. rHeader := http.Header{}
  224. conn, _, err := dialer.Dial(c.protocol+"://"+c.Address+c.Endpoint, rHeader) // nolint:bodyclose
  225. if err != nil {
  226. return err
  227. }
  228. c.conn = conn
  229. return nil
  230. }
  231. // reconnect tries to redial up to maxReconnectAttempts with exponential
  232. // backoff.
  233. func (c *WSClient) reconnect() error {
  234. attempt := 0
  235. c.mtx.Lock()
  236. c.reconnecting = true
  237. c.mtx.Unlock()
  238. defer func() {
  239. c.mtx.Lock()
  240. c.reconnecting = false
  241. c.mtx.Unlock()
  242. }()
  243. for {
  244. jitter := time.Duration(tmrand.Float64() * float64(time.Second)) // 1s == (1e9 ns)
  245. backoffDuration := jitter + ((1 << uint(attempt)) * time.Second)
  246. c.Logger.Info("reconnecting", "attempt", attempt+1, "backoff_duration", backoffDuration)
  247. time.Sleep(backoffDuration)
  248. err := c.dial()
  249. if err != nil {
  250. c.Logger.Error("failed to redial", "err", err)
  251. } else {
  252. c.Logger.Info("reconnected")
  253. if c.onReconnect != nil {
  254. go c.onReconnect()
  255. }
  256. return nil
  257. }
  258. attempt++
  259. if attempt > c.maxReconnectAttempts {
  260. return fmt.Errorf("reached maximum reconnect attempts: %w", err)
  261. }
  262. }
  263. }
  264. func (c *WSClient) startReadWriteRoutines() {
  265. c.wg.Add(2)
  266. c.readRoutineQuit = make(chan struct{})
  267. go c.readRoutine()
  268. go c.writeRoutine()
  269. }
  270. func (c *WSClient) processBacklog() error {
  271. select {
  272. case request := <-c.backlog:
  273. if c.writeWait > 0 {
  274. if err := c.conn.SetWriteDeadline(time.Now().Add(c.writeWait)); err != nil {
  275. c.Logger.Error("failed to set write deadline", "err", err)
  276. }
  277. }
  278. if err := c.conn.WriteJSON(request); err != nil {
  279. c.Logger.Error("failed to resend request", "err", err)
  280. c.reconnectAfter <- err
  281. // requeue request
  282. c.backlog <- request
  283. return err
  284. }
  285. c.Logger.Info("resend a request", "req", request)
  286. default:
  287. }
  288. return nil
  289. }
  290. func (c *WSClient) reconnectRoutine() {
  291. for {
  292. select {
  293. case originalError := <-c.reconnectAfter:
  294. // wait until writeRoutine and readRoutine finish
  295. c.wg.Wait()
  296. if err := c.reconnect(); err != nil {
  297. c.Logger.Error("failed to reconnect", "err", err, "original_err", originalError)
  298. c.Stop()
  299. return
  300. }
  301. // drain reconnectAfter
  302. LOOP:
  303. for {
  304. select {
  305. case <-c.reconnectAfter:
  306. default:
  307. break LOOP
  308. }
  309. }
  310. err := c.processBacklog()
  311. if err == nil {
  312. c.startReadWriteRoutines()
  313. }
  314. case <-c.Quit():
  315. return
  316. }
  317. }
  318. }
  319. // The client ensures that there is at most one writer to a connection by
  320. // executing all writes from this goroutine.
  321. func (c *WSClient) writeRoutine() {
  322. var ticker *time.Ticker
  323. if c.pingPeriod > 0 {
  324. // ticker with a predefined period
  325. ticker = time.NewTicker(c.pingPeriod)
  326. } else {
  327. // ticker that never fires
  328. ticker = &time.Ticker{C: make(<-chan time.Time)}
  329. }
  330. defer func() {
  331. ticker.Stop()
  332. c.conn.Close()
  333. // err != nil {
  334. // ignore error; it will trigger in tests
  335. // likely because it's closing an already closed connection
  336. // }
  337. c.wg.Done()
  338. }()
  339. for {
  340. select {
  341. case request := <-c.send:
  342. if c.writeWait > 0 {
  343. if err := c.conn.SetWriteDeadline(time.Now().Add(c.writeWait)); err != nil {
  344. c.Logger.Error("failed to set write deadline", "err", err)
  345. }
  346. }
  347. if err := c.conn.WriteJSON(request); err != nil {
  348. c.Logger.Error("failed to send request", "err", err)
  349. c.reconnectAfter <- err
  350. // add request to the backlog, so we don't lose it
  351. c.backlog <- request
  352. return
  353. }
  354. case <-ticker.C:
  355. if c.writeWait > 0 {
  356. if err := c.conn.SetWriteDeadline(time.Now().Add(c.writeWait)); err != nil {
  357. c.Logger.Error("failed to set write deadline", "err", err)
  358. }
  359. }
  360. if err := c.conn.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
  361. c.Logger.Error("failed to write ping", "err", err)
  362. c.reconnectAfter <- err
  363. return
  364. }
  365. c.mtx.Lock()
  366. c.sentLastPingAt = time.Now()
  367. c.mtx.Unlock()
  368. c.Logger.Debug("sent ping")
  369. case <-c.readRoutineQuit:
  370. return
  371. case <-c.Quit():
  372. if err := c.conn.WriteMessage(
  373. websocket.CloseMessage,
  374. websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""),
  375. ); err != nil {
  376. c.Logger.Error("failed to write message", "err", err)
  377. }
  378. return
  379. }
  380. }
  381. }
  382. // The client ensures that there is at most one reader to a connection by
  383. // executing all reads from this goroutine.
  384. func (c *WSClient) readRoutine() {
  385. defer func() {
  386. c.conn.Close()
  387. // err != nil {
  388. // ignore error; it will trigger in tests
  389. // likely because it's closing an already closed connection
  390. // }
  391. c.wg.Done()
  392. }()
  393. c.conn.SetPongHandler(func(string) error {
  394. // gather latency stats
  395. c.mtx.RLock()
  396. t := c.sentLastPingAt
  397. c.mtx.RUnlock()
  398. c.PingPongLatencyTimer.UpdateSince(t)
  399. c.Logger.Debug("got pong")
  400. return nil
  401. })
  402. for {
  403. // reset deadline for every message type (control or data)
  404. if c.readWait > 0 {
  405. if err := c.conn.SetReadDeadline(time.Now().Add(c.readWait)); err != nil {
  406. c.Logger.Error("failed to set read deadline", "err", err)
  407. }
  408. }
  409. _, data, err := c.conn.ReadMessage()
  410. if err != nil {
  411. if !websocket.IsUnexpectedCloseError(err, websocket.CloseNormalClosure) {
  412. return
  413. }
  414. c.Logger.Error("failed to read response", "err", err)
  415. close(c.readRoutineQuit)
  416. c.reconnectAfter <- err
  417. return
  418. }
  419. var response types.RPCResponse
  420. err = json.Unmarshal(data, &response)
  421. if err != nil {
  422. c.Logger.Error("failed to parse response", "err", err, "data", string(data))
  423. continue
  424. }
  425. if err = validateResponseID(response.ID); err != nil {
  426. c.Logger.Error("error in response ID", "id", response.ID, "err", err)
  427. continue
  428. }
  429. // TODO: events resulting from /subscribe do not work with ->
  430. // because they are implemented as responses with the subscribe request's
  431. // ID. According to the spec, they should be notifications (requests
  432. // without IDs).
  433. // https://github.com/tendermint/tendermint/issues/2949
  434. // c.mtx.Lock()
  435. // if _, ok := c.sentIDs[response.ID.(types.JSONRPCIntID)]; !ok {
  436. // c.Logger.Error("unsolicited response ID", "id", response.ID, "expected", c.sentIDs)
  437. // c.mtx.Unlock()
  438. // continue
  439. // }
  440. // delete(c.sentIDs, response.ID.(types.JSONRPCIntID))
  441. // c.mtx.Unlock()
  442. // Combine a non-blocking read on BaseService.Quit with a non-blocking write on ResponsesCh to avoid blocking
  443. // c.wg.Wait() in c.Stop(). Note we rely on Quit being closed so that it sends unlimited Quit signals to stop
  444. // both readRoutine and writeRoutine
  445. c.Logger.Info("got response", "id", response.ID, "result", fmt.Sprintf("%X", response.Result))
  446. select {
  447. case <-c.Quit():
  448. case c.ResponsesCh <- response:
  449. }
  450. }
  451. }
  452. ///////////////////////////////////////////////////////////////////////////////
  453. // Predefined methods
  454. // Subscribe to a query. Note the server must have a "subscribe" route
  455. // defined.
  456. func (c *WSClient) Subscribe(ctx context.Context, query string) error {
  457. params := map[string]interface{}{"query": query}
  458. return c.Call(ctx, "subscribe", params)
  459. }
  460. // Unsubscribe from a query. Note the server must have a "unsubscribe" route
  461. // defined.
  462. func (c *WSClient) Unsubscribe(ctx context.Context, query string) error {
  463. params := map[string]interface{}{"query": query}
  464. return c.Call(ctx, "unsubscribe", params)
  465. }
  466. // UnsubscribeAll from all. Note the server must have a "unsubscribe_all" route
  467. // defined.
  468. func (c *WSClient) UnsubscribeAll(ctx context.Context) error {
  469. params := map[string]interface{}{}
  470. return c.Call(ctx, "unsubscribe_all", params)
  471. }