How error is defined in common http library? Can data and error co-exist? - node.js

A callback function used in http request library usually has a parameter for error and 1 (or 2) more for the response content.
However, I cannot find a clear definition of the error object and the relationship between the error and response object (mainly if they can co-exist).
For Q1, my first impression is that it can be classified by the status code. If so, an error in http can only have one of two categories (client/ server)?
For Q2, I believe it makes sense in some scenario to have both. For example, it is possible a server responses a 451 Unavailable For Legal Reasons, but still return some fields by best effort?

"Can data and error co-exist?"
Yes, they can co-exist. Actually, according to RFC7231 (HTTP Semantics and Content)
3.3. Payload Semantics
...
Response messages with an error status code
usually contain a payload that represents the error condition, such
that it describes the error state and what next steps are suggested
for resolving it.
"How error is defined in common http library?"
This is HTTP library implementation logic. As anyone can develop an HTTP library, parse response payload and do whatever he/she want, the "how error is defined" question is mainly decided by library designer, and does not have a criteria to answer.

Related

Why does PSI API put values of originLoadingExperience in loadingExperience, in case CRuX does not have sufficient real-world speed data for the page?

In case the Chrome User Experience Report does not have sufficient real-world speed data for the page, the response of the PSI API (v5) does contain values for all properties of loadingExperience in the response. These values are exactly the same as the values for originLoadingExperience.
The problem with this is that from the API response you can't know if the data in loadingExperience is valid or the duplicate of originLoadingExperience.
Sure, it's possible to compare all those values and if all match exactly it is kinda safe to conclude it's a case of duplication, but this is not bullet-proof and requires extra code.
Is there a way to reliably know from the API response if CRuX did not have sufficient data for the page?
Yes I've seen this too and I consider it a bug in the PSI API. I've already flagged it with the PSI team suggesting that they include an error message in the loadingExperience field to clarify that it doesn't have sufficient data for the page.

REST API what is the proper way of URI naming using nouns and not verbs?

I have a login and I need to do something like this:
1. POST .../authentication/login
2. POST .../authentication/verifyToken
3. POST .../authentication/forgotPassword
Will ask for a phone and a password.
Will ask for an auth token.
Will ask for a phone and a password.
But as I read, this structure is not good since it contains verbs rather than nouns.
I have tried to make something like this:
1. POST .../sessions/new
2. GET .../sessions/:token
3. GET .../sessions/forgot
1. Will create a new token, based on phone and password correct credentials.
2. Will verify the token validation or expiration.
3. Will send a SMS within a new password or a new temporary password reset code.
This first method is not REST. But its totally clear.
You can read the URL and understand exactly what it gonna to do. You do not need any kind of explanation.
However, more and more articles say that verbs in REST is not RESTFUL and thus, not a good practice to achieve.
What is the proper way of handle this?
REST doesn't care what spelling you use for your resource identifiers.
But as I read, this structure is not good since it contains verbs rather than nouns.
The structure is fine.
You can read the URL and understand exactly what it gonna to do.
Right -- REST does not care if you can read the URL and understand what it is going to do.
URL/URI are identifiers, in the same way that variable names in your program are identifiers. Your compiler doesn't particularly care whether your variable is named accountBalance, purpleMonkeyDishwasher, or x. The spellings described in our coding standards are for human readers, and the same is true for hackable urls.
However, more and more articles say that verbs in REST is not RESTFUL and thus, not a good practice to achieve.
REST is an architectural style
As an architectural style for network-based applications, its definition is presented in the dissertation incrementally, as an accumulation of design constraints that derive from nine pre-existing architectural styles and five additional constraints unique to the Web
Fielding describes the constraints in his thesis; any who claim that verbs in identifiers "are not RESTful" should be able to point to a specific constraint that they violate.
I have yet to see a compelling argument that any of the REST constraints are violated by identifier spellings.
First I would not use the term session. This implies a server side state, what is problematic in stateless communication as REST requires.
So your problem could be solved by modeling resources, probably like:
GET ./authentication/token
to get a token if valid credentials provided in the request headers.
GET ./authentication/password
to get a new temporary password if E-mail address provided in the request headers.
You also can use POST in order to transport values in the request body.
Be aware of that the service should answer with an HTTP 204 in case of the result is being sent by SMS.

Tracker GET request parameters in Bittorrent

When using Bittorrent, I saw there are the parameters "numwant", "corrupt" and "key" in URL.
However, I found these paremeters don't be defined in BEP 3 (http://www.bittorrent.org/beps/bep_0003.html), so could someone tell me the meaning of the parameters, and where are the 3 parameters defined?
Also, before asking the questsion, I had searched the keyword "numwant" in the site www.bittorrent.org, and just found "numwant" appears in BEP 8, but the definition or explanation of the keyword can't be found.
While BEP3 is official, it's a terse and dense document. I would instead recommend you to use the inofficial: https://wiki.theory.org/index.php/BitTorrentSpecification
It's a lot easier to read and understand. It also document some early extensions to the protocol that you can't find elsewhere.
There you will find:
numwant: Optional. Number of peers that the client would like to receive from the tracker. This value is permitted to be zero. If omitted, typically defaults to 50 peers.
key: Optional. An additional identification that is not shared with any other peers. It is intended to allow a client to prove their identity should their IP address change.
Regarding corrupt, there is afaik no written documentation how it is defined, but it's rather simple; When a piece fails the hash check, that amount of data is accounted on the corrupt counter instead of the downloaded counter.
There is also a similar redundant counter, where data that is discharged because it's redundant is acconuted. This happens, for example, in end game mode, when the same chunk is requested from more than one peer.
Also, there is some additional info in my answer here: Understanding Bittorrent Tracker Request

Error first callbacks vs "success" and "failed" callbacks

So far in programming (Swift for iOS) for async functions i've been using two callbacks to handle the completion of the async function. One is executed if the function completes without error ("success") and the other if the function errors ("failed").
I've noticed that node.js uses error first callbacks where the first parameter of the callback is an error which is null if no error occurs. It then comes down to the user to check if the error is null and handle the situation appropriately based on the result of this check.
My question is; is there any reason, in the realms of optimisation or best practices in programming, to use either of these methods over the other, or does it come down to personal preference and consistency?
Personally I can't see how it would matter that much either way but my concern is I may have missed something.

Command Query Separation: commands must return void?

If CQS prevents commands from returning status variables, how does one code for commands that may not succeed? Let's say you can't rely on exceptions.
It seems like anything that is request/response is a violation of CQS.
So it would seem like you would have a set of "mother may I" methods giving the statuses that would have been returned by the command. What happens in a multithreaded / multi computer application?
If I have three clients looking to request that a server's object increase by one (and the object has limits 0-100). All check to see if they can but one gets it - and the other two can't because it just hit a limit. It would seem like a returned status would solve the problem here.
It seems like anything that is request/response is a violation of CQS.
Pretty much yes, hence Command-Query-Separation. As Martin Fowler nicely puts it:
The fundamental idea is that we should divide an object's methods into two sharply separated categories:
Queries: Return a result and do not change the observable state of the system (are free of side effects).
Commands: Change the state of a system but do not return a value [my emphasis].
Requesting that a server's object increase by one is a Command, so it should not return a value - processing a response to that request means that you are doing a Command and Query action at the same time which breaks the fundamental tenet of CQS.
So if you want to know what the server's value is, you issue a separate Query.
If you really need a request-response pattern, you either need to have something like a convoluted callback event process to issue queries for the status of a specific request, or pure CQS isn't appropriate for this part of your system - note the word pure.
Multithreading is a main drawback of CQS and can make it can hard to do. Wikipedia has a basic example and discussion of this and also links to the same Martin Fowler article where he suggests it is OK to break the pattern to get something done without driving yourself crazy:
[Bertrand] Meyer [the inventor of CQS] likes to use command-query separation absolutely, but there are
exceptions. Popping a stack is a good example of a query that modifies
state. Meyer correctly says that you can avoid having this method, but
it is a useful idiom. So I prefer to follow this principle when I can,
but I'm prepared to break it to get my pop.
TL;DR - I would probably just look at returning a response, even tho it isn't correct CQS.
Article "Race Conditions Don’t Exist" may help you to look at the problem with CQS/CQRS mindset.
You may want to step back and ask why counter value is absolutely necessary to know before sending a command? Apparently, you want to make decision on the client side whether you can increase counter more or not.
The approach is to let the server make such decision. Let all the clients send commands (some will succeed and some will fail). Eventually clients will get consistent view of the server object state (where limit has reached) and may finally stop sending such commands.
This time window of inconsistency leads to wrong decisions by the clients, but it never breaks consistency of the object (or domain model) on the server side as long as commands are handled adequately.

Resources