Transactional Operations
If you want to group several operations in order to make them transactional, MibServer API provides a service based on OData Batch Processing specifications.
1 - Batch Request
Batch request allows grouping multiple operations into a single HTTP request payload using Multipart MIME v1.0 message (RFC 2046). Each part should be the full message to an API URL (Simple operations), including the headers and payload.
2 - Batch Request Headers
The batch request is a POST verb with a content-type header set to "multipart/mixed" and a boundary specification as defined in [RFC2046].
POST /api/v1/$batch HTTP/1.1
Host: mediaibox.mydomain.com
Authorization: Bearer mYs3cr3tT0k3n
Accept: application/vnd.api+json
Content-Type: multipart/mixed; boundary=batch_unique_guid
<Batch Request Body>
3 - Batch Request Body
The body of batch requests contains boundary tag, representing a list of transactional operations. The tag boundary is equivalent to a HTTP header containing a content-type set to "application/http; msgtype=request" and annotated in an outer part of multipart body. The parts won't have authorization header, this is only present in real header. A tag boundary contains a list of operations, headers and bodies, each operation as a part of Multipart MIME, delimited by tag boundary
For example, if we'd like to insert three genres in the same transaction, the batch request would be:
POST /api/v1/$batch HTTP/1.1
Host: mediaibox.mydomain.com
Authorization: Bearer mYs3cr3tT0k3n
Accept: application/vnd.api+json
Content-Type: multipart/mixed; boundary=batch_unique_guid
--batch_unique_guid
Content-Type: application/http; msgtype=request
POST /api/v1/mvp_genres HTTP/1.1
Host: mediaibox.mydomain.com
Accept: application/vnd.api+json
Content-Type: application/vnd.api+json
{
"mvp_genres": [{
"name": "Comedy",
}]
}
--batch_unique_guid
Content-Type: application/http; msgtype=request
POST /api/v1/mvp_genres HTTP/1.1
Host: mediaibox.mydomain.com
Accept: application/vnd.api+json
Content-Type: application/vnd.api+json
{
"mvp_genres": [{
"name": "Action",
}]
}
--batch_unique_guid
Content-Type: application/http; msgtype=request
POST /api/v1/mvp_genres HTTP/1.1
Host: mediaibox.mydomain.com
Accept: application/vnd.api+json
Content-Type: application/vnd.api+json
{
"mvp_genres": [{
"name": "Sci-fi",
}]
}
--batch_unique_guid--
4 - Batch Response
In a Batch Request the execution order of tag boundary is the same order received. If an error is thrown after any operation, the transaction is rolled back immediately, without executing subsequents operations.
If all headers are valid, batch request will return a 200 Accepted HTTP response code to indicate that the request was accepted for processing, but the processing yet to be completed. The requests within the body of the batch may subsequently fail or be malformed; however, this enables batch implementations to stream the results.
If the service receives a batch request with an invalid set of headers it will return a 4xx response code and perform no further processing of the request.
The batch response body must match with structured defined on request body, such that the same multipart MIME message structure defined for requests is used for responses. The exception to this rule is that when a request within a tag boundary fails, the tag boundary response is not represented using the "application/http; msgtype=request" media type, but, using the "application/http; msgtype=response" media type.
Success Response:
--batch_unique_guid
Content-Type: application/http; msgtype=response
HTTP/1.1 201 Created
Location: /api/v1/mvp_genres/1006
ETag: "beWUeaOrloMzp0Kv-unoqg"
Content-Type: application/vnd.api+json
{"_meta":{"_pageCount":1,"_filterRowCount":1,"_pageSize":20,"_previousPage":"","_nextPage":"","_mainMediaType":"mvp_genres","_ids":[1006],"_childMediaType":null,"_include":[],"_sortOrder":{},"_fields":{},"_filter":{"_root":null},"_page":0,"_hideMeta":false,"_hideLinks":false},"_links":{"mvp_genres.owner":{"_href":"/api/v1/adm_users/{mvp_genres.owner}","_type":"adm_users"}},"mvp_genres":[{"_id":1006,"_href":"/api/v1/mvp_genres/1006","_type":"mvp_genres","_etag":"beWUeaOrloMzp0Kv-unoqg","dateins":1432247389,"name":"Comedy","_links":{"owner":1}}],"_linked":{}}
--batch_unique_guid
Content-Type: application/http; msgtype=response
HTTP/1.1 201 Created
Location: /api/v1/mvp_genres/1007
ETag: "letaU8l6ulvu26bKv8s7tg"
Content-Type: application/vnd.api+json
{"_meta":{"_pageCount":1,"_filterRowCount":1,"_pageSize":20,"_previousPage":"","_nextPage":"","_mainMediaType":"mvp_genres","_ids":[1007],"_childMediaType":null,"_include":[],"_sortOrder":{},"_fields":{},"_filter":{"_root":null},"_page":0,"_hideMeta":false,"_hideLinks":false},"_links":{"mvp_genres.owner":{"_href":"/api/v1/adm_users/{mvp_genres.owner}","_type":"adm_users"}},"mvp_genres":[{"_id":1007,"_href":"/api/v1/mvp_genres/1007","_type":"mvp_genres","_etag":"letaU8l6ulvu26bKv8s7tg","dateins":1432247389,"name":"Action","_links":{"owner":1}}],"_linked":{}}
--batch_unique_guid
Content-Type: application/http; msgtype=response
HTTP/1.1 201 Created
Location: /api/v1/mvp_genres/1008
ETag: "rU44W-zHd3iNZgftdMhSRA"
Content-Type: application/vnd.api+json
{"_meta":{"_pageCount":1,"_filterRowCount":1,"_pageSize":20,"_previousPage":"","_nextPage":"","_mainMediaType":"mvp_genres","_ids":[1008],"_childMediaType":null,"_include":[],"_sortOrder":{},"_fields":{},"_filter":{"_root":null},"_page":0,"_hideMeta":false,"_hideLinks":false},"_links":{"mvp_genres.owner":{"_href":"/api/v1/adm_users/{mvp_genres.owner}","_type":"adm_users"}},"mvp_genres":[{"_id":1008,"_href":"/api/v1/mvp_genres/1008","_type":"mvp_genres","_etag":"rU44W-zHd3iNZgftdMhSRA","dateins":1432247389,"name":"Sci-fi","_links":{"owner":1}}],"_linked":{}}
--batch_unique_guid--
Failed Response:
--batch_unique_guid
Content-Type: application/http; msgtype=response
HTTP/1.1 400 Bad Request
Content-Type: application/vnd.api+json; charset=utf-8
{"error":"persistence_mediatypewithdistinctnames","error_message":"error message..."}
--batch_unique_guid
Content-Type: application/http; msgtype=response
HTTP/1.1 400 Bad Request
Content-Type: application/vnd.api+json; charset=utf-8
{"error":"persistence_mediatypewithdistinctnames","error_message":"error message..."}
--batch_unique_guid
Content-Type: application/http; msgtype=response
HTTP/1.1 400 Bad Request
Content-Type: application/vnd.api+json; charset=utf-8
{"error":"persistence_mediatypewithdistinctnames","error_message":"error message..."}
--batch_unique_guid--
5 - Batch referencing
Now you are probably thinking why you should use batch requests when you can simply use an array to do several operations as seen previously in Create multiple entities, Update multiple entities and Delete multiple entities. Batch requests are more complex and powerful than those operations, and allows you to cascade several different operations in one single transaction, even for different media types.
If you apply what you saw in Create multiple entities, you can create several entities of the same media type. But if you want to create a new genre, create a new movie and then create a relationship between both in a single transaction?
With batch requests you can even get the ID generated in a part and use it in the next parts. Every POST part may have a Content-ID header with some value determined by client. When batch request processes one POST part with Content-ID (My_BatchReference_123, for instance), it assigns to a variable called ${Content-ID} ($My_BatchReference_123) the newly created ID for using in headers, or if you want to use it inside the body, you can use the variable ${Content-ID}.
So let's pretend that we want to insert the Comedy genre, the Charles Chaplin Productions as a new producer, and a new movie called Modern Times, related to the newly created entities above.
POST /api/v1/$batch HTTP/1.1
Host: mediaibox.mydomain.com
Authorization: Bearer mYs3cr3tT0k3n
Content-Type: multipart/mixed; boundary=batch_unique_guid
--batch_unique_guid
Content-Type: application/http; msgtype=request
POST /api/v1/mvp_genres HTTP/1.1
Host: mediaibox.mydomain.com
Accept: application/vnd.api+json
Content-Type: application/vnd.api+json
Content-Id: BATCH_REF_MVP_GENRES_CREATION
{
"mvp_genres": [
{
"name": "Comedy",
}
]
}
--batch_unique_guid
Content-Type: application/http; msgtype=request
POST /api/v1/mvp_producers HTTP/1.1
Host: mediaibox.mydomain.com
Accept: application/vnd.api+json
Content-Type: application/vnd.api+json
Content-Id: BATCH_REF_MVP_PRODUCERS_CREATION
{
"mvp_producers": [
{
"name": "Charles Chaplin Productions",
"title": "Charles Chaplin Productions"
}
]
}
--batch_unique_guid
Content-Type: application/http; msgtype=request
POST /api/v1/mvp_movies HTTP/1.1
Host: mediaibox.mydomain.com
Accept: application/vnd.api+json
Content-Type: application/vnd.api+json
Content-Id: BATCH_REF_MVP_MOVIES_CREATION
{
"mvp_movies": [
{
"name": "Modern Times",
"country": "USA",
"year": "1936",
"producer_id" : "$BATCH_REF_MVP_PRODUCERS_CREATION"
}
]
}
--batch_unique_guid
Content-Type: application/http; msgtype=request
POST /api/v1/mvp_genres/$BATCH_REF_MVP_GENRES_CREATION/mvp_movies HTTP/1.1
Host: mediaibox.mydomain.com
Accept: application/vnd.api+json
Content-Type: application/vnd.api+json
{
"mvp_movies": {
"operation" : "Add",
"values" : [ "$BATCH_REF_MVP_MOVIES_CREATION" ]
}
}
--batch_unique_guid--
Four steps (parts) were declared in above example. It could be reduced to three in a real situation, but this document aims to cover different scenarios and the last step shows how reference request in the header of a subsequent part. If you try to use the result of a part in a previous part an exception will be thrown, because the parts are evaluated sequentially.
First step creates the comedy genre. It's Content-ID is BATCH_REF_MVP_GENRES_CREATION, in other words, the variable $BATCH_REF_MVP_GENRES_CREATION will be set with the comedy ID when inserted. Second step creates the new producer and sets the variable $BATCH_REF_MVP_PRODUCERS_CREATION to newly created producer ID. Third step creates a movie and uses the producer created in step 2, through the following reference:
{
"mvp_movies": [
{
"name": "Modern Times",
"country": "USA",
"year": "1936",
"producer_id" : "$BATCH_REF_MVP_PRODUCERS_CREATION"
}
]
}
The first (and only) ID generated in step with Content-ID equals to BATCH_REF_MVP_PRODUCERS_CREATION will be used as the producer_id of this movie. Comedy could be referenced this way, but the sample would not cover all possibilities. Instead, a fourth step shows the reference in header:
POST /api/v1/mvp_genres/$BATCH_REF_MVP_GENRES_CREATION/mvp_movies HTTP/1.1
Besides referencing $1 in the header, the body also references the movie ID generated in step of content ID $BATCH_REF_MVP_MOVIES_CREATION.
{
"mvp_movies": {
"operation" : "Add",
"values" : [ "$BATCH_REF_MVP_MOVIES_CREATION" ]
}
}
The finder object called "resultFromRequest" used to reference is obsolete and will be removed in the future.
6 - Batch Replacement Engine
6.1 - Replacement Of The Body Content
The replacement of batch reference occurs in the JSON body.
{ "mvp_movies": [ { "name": "Modern Times", "_links": { "producer_id": {
"Operation" : "Add",
"values" : "$batch_producer_id"
} } } ] }
Changing to:
{ "mvp_movies": [ { "name": "Modern Times", "_links": { "producer_id": {
"Operation" : "Add",
"values" : 345 // <- replacement
} } } ] }
6.2 - Replacing Fields
You can set the reference directly into the field.
{ "mvp_movies": [ { "name": "Modern Times", "producer_id": "$batch_producer_id" } ] }
6.3 - Relationships 1x1 and 1xN
For 1x1 relationships you can set the reference directly into the field.
{ "mvp_movies": [ { "name": "Modern Times", "producer_id": "$batch_producer_id" } ] }
Also is valid to set reference via links structure.
{ "mvp_movies": [ { "name": "Modern Times", "_links": { "producer_id": {
"operation": "Add",
"values": [ "$batch_producer_id" ]
} } } ] }
However, for relationships 1xN is only via links structure.
{ "mvp_movies": [ { "name": "Modern Times", "_links": { "mmedias": {
"operation":"Add",
"values": [ "$batch_mmedias_ids" ] //[ 34,54,67,102 ]
} } } ] }
6.4 - Replacement Into Text Field Types
//batchHeader = { "batch_sample_ids" : "12,34,55", "batch_sample_id" : "13" } { "mvp_movies": [ { "name": "Ids :$batch_sample_ids Id:$batch_sample_id test" //"name": "Ids :12,34,55 Id:13 test" } ] }
6.5 - Referencing One Id Of A Part That Created Several
A part that creates several entities (Create multiple entities, or $bulkcreate) assigns all its new ids to its Content-ID, comma-separated and in the order of its body. $My_Reference is replaced by that whole list, and $My_Reference[i] by the i-th id, counting from 0.
{ "mvp_genres_metadatas": [ { "genre_id": "$batch_genres[0]", "title": "Comedy" }, { "genre_id": "$batch_genres[1]", "title": "Action" } ] }
Changing to:
{ "mvp_genres_metadatas": [ { "genre_id": 39, "title": "Comedy" }, { "genre_id": 40, "title": "Action" } ] }
The quotes around a reference are part of what is replaced, which is why the example writes each reference as a whole JSON string. An index beyond the ids of that part fails the part, and with it the batch.
7 - Bulk Parts
$bulkcreate and $bulkdelete (see Simple Operations, 8.1 and 13.1) are regular parts of a batch. They are meant for the case where one operation creates or deletes a large structure: a parent, its many children, and rows that point at each child.
POST /api/v1/$batch HTTP/1.1
Host: mediaibox.mydomain.com
Authorization: Bearer mYs3cr3tT0k3n
Content-Type: multipart/mixed; boundary=batch_unique_guid
--batch_unique_guid
Content-Type: application/http; msgtype=request
POST /api/v1/mvp_genres/$bulkcreate HTTP/1.1
Host: mediaibox.mydomain.com
Accept: application/vnd.api+json
Content-Type: application/vnd.api+json
Content-Id: batch_genres
Prefer: return=minimal
{
"mvp_genres": [ { "name": "Comedy" }, { "name": "Action" } ]
}
--batch_unique_guid
Content-Type: application/http; msgtype=request
POST /api/v1/mvp_genres_metadatas/$bulkcreate HTTP/1.1
Host: mediaibox.mydomain.com
Accept: application/vnd.api+json
Content-Type: application/vnd.api+json
Prefer: return=minimal
{
"mvp_genres_metadatas": [
{ "genre_id": "$batch_genres[0]", "title": "Comedy" },
{ "genre_id": "$batch_genres[1]", "title": "Action" }
]
}
--batch_unique_guid--
A batch that carries a bulk part is strict from that part on. A failing part rolls back the whole batch in any batch, as described in Batch Response. From the first bulk part on, the batch is also rolled back when something fails between parts (the request is cancelled, or a part cannot be read), so a large create or delete is either complete or not there at all. A part counts as a bulk part when its path ends in /$bulkcreate or /$bulkdelete.
With Prefer: return=minimal on its bulk parts, the batch response does not carry every created entity back: each part answers only its new ids, which is all a later part needs to reference them.
7.1 - From .NET code
Code that runs on MediaiBox.Core (MibClient2) — a repository listener, an agent, a seed — gets the same set-based writes from IMibRepository (MIB 7.0.6, MEDIAIBOX-12357):
CreateManyAsync(IReadOnlyList<IMibObjectAsync> objects, CancellationToken ct, int userId = 0, bool? storeHistory = null)inserts new objects (ID 0) with the same result and repository events as saving each one, in the order given — each object receives its id, in that order.DeleteManyAsync(IReadOnlyList<IMibObjectAsync> objects, CancellationToken ct, int userId = 0, bool? storeHistory = null)does the same for deletes.
Both run on each object's ReferenceSql, inside its open transaction when there is one, and never open or commit one. The database repository writes in sets on SQL Server; the interface's default implementation, which other repositories inherit, saves or deletes one object at a time. A notification listener that implements IRepositoryBulkNotificationListener receives the events grouped per media type — see Auditing.
MIB 7.1 adds the matching set-based reads (MEDIAIBOX-12382):
FindAllLoadedAsync<T>(mediaType, queryFilter, queryParameters, order, sql, ct)returns whatFindAllAsync<T>followed byPreloadAsync(false)returns, in one statement (alsoMibObjectEx<T>.FindAllLoadedAsync);GetDirectRelatedObjectIdsManyAsync(...)andGetRelatedObjectIdsManyAsync(...)return the related ids of many objects at once, keyed by each object's id and in the order the per-object call returns them (see the note on ordering in Simple Operations, 5.1).