26
Modified: Sun Nov 28 2021, 20:49:24 Humla v0.3 Middleware Architectures 1 Lecture 4: HATEOAS, Caching and Concurrency doc. Ing. Tomáš Vitvar, Ph.D. [email protected] • @TomasVitvar • https://vitvar.com Czech Technical University in Prague Faculty of Information Technologies • Software and Web Engineering • https://vitvar.com/lectures

Middleware Architectures 1

  • Upload
    others

  • View
    1

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Middleware Architectures 1

Modified:SunNov282021,20:49:24Humlav0.3

MiddlewareArchitectures1Lecture4:HATEOAS,CachingandConcurrency

doc.Ing.TomášVitvar,[email protected]•@TomasVitvar•https://vitvar.com

CzechTechnicalUniversityinPragueFacultyofInformationTechnologies•SoftwareandWebEngineering•https://vitvar.com/lectures

Page 2: Middleware Architectures 1

Overview

HATEOASCaching,Revalidation,ConcurrencyControlRichardsonMaturiyModel

Lecture4:HATEOAS,CachingandConcurrency,CTUWinterSemester2021/2022,@TomasVitvar ‒2‒

Page 3: Middleware Architectures 1

HATEOAS

HATEOAS=HypertextastheEngineforApplicationState‒TheRESTcoreprinciple‒Hypertext→Hypertextisarepresentationofaresourcestatewithlinks

→AlinkisanURIofaresource→Applyinganaccess(PUT,POST,DELETE)toaresourceviaitslink=statetransition

Statelessness‒Aservicedoesnotuseasessionmemorytorememberastate

‒HATEOASenablesstatelessimplementationofservicesLecture4:HATEOAS,CachingandConcurrency,CTUWinterSemester2021/2022,@TomasVitvar ‒3‒

Page 4: Middleware Architectures 1

StatefulserverSessionstostoretheapplicationstate‒Theappusesaservermemorytorememberthestate‒Whentheserverrestarts,theappstateislost

Lecture4:HATEOAS,CachingandConcurrency,CTUWinterSemester2021/2022,@TomasVitvar ‒4‒

Page 5: Middleware Architectures 1

StatelessserverHTTPandhypermediatotransfertheappstate‒Doesnotuseaservermemorytoremembertheappstate‒StatetransferredbetweenaclientandaserviceviaHTTPmetadataandresources'representations

Lecture4:HATEOAS,CachingandConcurrency,CTUWinterSemester2021/2022,@TomasVitvar ‒5‒

Page 6: Middleware Architectures 1

PersistentStorageandSessionMemoryPersistentStorage‒Containstheappdata‒Dataisserializedintoresourcerepresentationformats‒AllsessionsmayaccessthedataviaresourceIDsSessionMemory‒Servermemorythatcontainsastateoftheapp‒Asessionmayonlyaccessitssessionmemory‒Accessthroughcookies‒Note→Asessionmemorymaybeimplementedviaapersistentstorage(suchasinGoogleAppEngine)

Lecture4:HATEOAS,CachingandConcurrency,CTUWinterSemester2021/2022,@TomasVitvar ‒6‒

Page 7: Middleware Architectures 1

LinkServiceoperation‒Applyinganaccesstoalink(GET,PUT,POST,DELETE)‒Link:HTTPmethod+resourceURI+optionallinksemanticsExample:getOrder,addOrder,andupdateItem

Lecture4:HATEOAS,CachingandConcurrency,CTUWinterSemester2021/2022,@TomasVitvar ‒7‒

Page 8: Middleware Architectures 1

AtomLinksAtomSyndicationFormat‒XML-baseddocumentformat;Atomfeeds‒AtomlinksbecomingpopularforRESTfulapplications

‒Linkstructurerel–nameofthelink~semanticsofanoperationbehindthelinkhref–URItotheresourcedescribedbythelinktype–mediatypeoftheresourcethelinkpointsto

12345678

<ordera:xmlns="http://www.w3.org/2005/Atom"xmlns="..."><a:linkrel="next"href="http://company.com/orders/5543"type="application/xml"/><customer>Tomas</customer><items>...</items></order>

Lecture4:HATEOAS,CachingandConcurrency,CTUWinterSemester2021/2022,@TomasVitvar ‒8‒

Page 9: Middleware Architectures 1

LinkSemanticsStandardrelvalues‒Navigation:next,previous,self‒DoesnotreflectaHTTPmethodyoucanuseExtensionrelvalues‒Youcanusereltoindicateasemanticsofanoperation‒Example:additem,deleteorder,updateorder,etc.‒Aclientassociatesthissemanticswithanoperationitmayapplyataparticularstate

‒ThesemanticsshouldbedefinedbyusinganURI1234567

<ordera:xmlns="http://www.w3.org/2005/Atom"xmlns="..."><id>2324</id><a:linkrel="http://company.com/op/addItem"href="http://company.com/orders/2324"/><a:linkrel="http://company.com/op/deleteOrder"href="http://company.com/orders/2324"/></order>

Lecture4:HATEOAS,CachingandConcurrency,CTUWinterSemester2021/2022,@TomasVitvar ‒9‒

Page 10: Middleware Architectures 1

LinkHeadersAnalternativetoAtomlinksinresourcerepresentations‒linksdefinedinHTTPLinkheader,WebLinkingIETFspec‒TheyhavethesamesemanticsasAtomLinks‒Example:

Advantages‒noneedtogettheentiredocument‒noneedtoparsethedocumenttoretrievelinks‒useHTTPHEADonly

>HEAD/ordersHTTP/1.1<Content-Type:application/xml<Link:<http://company.com/orders/?page=2&size=10>;rel="next"<Link:<http://company.com/orders/?page=10&size=10>;rel="last"

Lecture4:HATEOAS,CachingandConcurrency,CTUWinterSemester2021/2022,@TomasVitvar ‒10‒

Page 11: Middleware Architectures 1

PreconditionsandHATEOASPreconditionsinHATEOAS‒Serviceinacurrentstategeneratesonlyvalidtransitionsthatitincludesintherepresentationoftheresource.

‒Transitionlogicisrealizedattheserver-side

Lecture4:HATEOAS,CachingandConcurrency,CTUWinterSemester2021/2022,@TomasVitvar ‒11‒

Page 12: Middleware Architectures 1

AdvantagesLocationtransparency‒only"entry-level"linkspublishedtotheWorld‒otherlinkswithindocumentscanchangewithoutchangingclient'slogic‒Hypertextrepresentsthecurrentuser'sview,i.e.rightsorothercontextLoosecoupling‒noneedforalogictoconstructthelinks‒ClientsknowtowhichstatestheycanmovevialinksStatelessnessandCloud‒Betterimplementationofscalability

Lecture4:HATEOAS,CachingandConcurrency,CTUWinterSemester2021/2022,@TomasVitvar ‒12‒

Page 13: Middleware Architectures 1

Overview

HATEOASCaching,Revalidation,ConcurrencyControlRichardsonMaturiyModel

Lecture4:HATEOAS,CachingandConcurrency,CTUWinterSemester2021/2022,@TomasVitvar ‒13‒

Page 14: Middleware Architectures 1

Scalability

Needforscalability‒HugeamountofrequestsontheWebeveryday‒HugeamountofdatadownloadedSomeexamples‒Google,Facebook:5billionAPIcalls/day‒Twitter:3billionsofAPIcalls/day(75%ofallthetraffic)→50milliontweetsaday

‒eBay:8billionAPIcalls/month‒Bing:3billionAPIcalls/month‒AmazonWS:over100billionobjectsstoredinS3ScalabilityinREST‒Cachingandrevalidation‒Concurrencycontrol

Lecture4:HATEOAS,CachingandConcurrency,CTUWinterSemester2021/2022,@TomasVitvar ‒14‒

Page 15: Middleware Architectures 1

Caching

Yourserviceshouldcache:‒anytimethereisastaticresource‒eventhereisadynamicresource→withchancesitupdatesoften→youcanforceclientstoalwaysrevalidate

threesteps:‒clientGETstheresourcerepresentation‒servercontrolshowitshouldcachethroughCache-Controlheader‒clientrevalidatesthecontentviaconditionalGET

Lecture4:HATEOAS,CachingandConcurrency,CTUWinterSemester2021/2022,@TomasVitvar ‒15‒

Page 16: Middleware Architectures 1

CacheHeadersCache-Controlresponseheader‒controlsoverlocalandproxycaches‒private–noproxyshouldcache,onlyclientscan‒public–anyintermediarycancache(proxiesandclients)‒no-cache–theresponseshouldnotbecached.Ifitiscached,thecontentshouldalwaysberevalidated.

‒no-store–mustnotstorepersistently(thisturnsoffcaching)‒no-transform–notransformationofcacheddata;e.g.compressions‒max-age,s-maxageatimeinsecondshowlongthecacheisvalid;s-maxageforproxies

Last-ModifiedandETagresponseheaders‒ContentlastmodifieddateandacontententitytagIf-Modified-SinceandIf-None-Matchrequestheaders‒Contentrevalidation(conditionalGET)

Lecture4:HATEOAS,CachingandConcurrency,CTUWinterSemester2021/2022,@TomasVitvar ‒16‒

Page 17: Middleware Architectures 1

ExampleDateRevalidationCachecontrolexample:

‒onlyclientcancache,thecacheisvalidfor200seconds.Revalidation(conditionalGET)example:‒Aclientrevalidatesthecacheafter200seconds.

>GET/ordersHTTP/1.1>...<HTTP/1.1200OK<Content-Type:application/xml<Cache-Control:private,max-age=200<Last-Modified:Sun,7Nov2011,09:40CET<<...data...

>GET/ordersHTTP/1.1>If-Modified-Since:Sun,7Nov2011,09:40CET<HTTP/1.1304NotModified<Cache-Control:private,max-age=200<Last-Modified:Sun,7Nov2011,09:40CET

Lecture4:HATEOAS,CachingandConcurrency,CTUWinterSemester2021/2022,@TomasVitvar ‒17‒

Page 18: Middleware Architectures 1

EntityTagsSignatureoftheresponsebody‒AhashsuchasMD5‒AsequencenumberthatchangeswithanymodificationofthecontentTypesoftag‒StrongETag:reflectsthecontentbitbybit‒WeakETag:reflectsthecontent"semantically"→Theappdefinesthemeaningofitsweaktags

ExamplecontentrevalidationwithETag<HTTP/1.1200OK<Cache-Control:private,max-age=200<Last-Modified:Sun,7Nov2011,09:40CET<ETag:"4354a5f6423b43a54d">GET/ordersHTTP/1.1>If-None-Match:"4354a5f6423b43a54d"<HTTP/1.1304NotModified<Cache-Control:private,max-age=200<Last-Modified:Sun,7Nov2011,09:40CET<ETag:"4354a5f6423b43a54d"

Lecture4:HATEOAS,CachingandConcurrency,CTUWinterSemester2021/2022,@TomasVitvar ‒18‒

Page 19: Middleware Architectures 1

DesignSuggestionsComposedresourcesuseweakETags‒Forexample/orders→acomposedresourcethatcontainsasummaryinformation→changestoanorder'sitemswillnotchangesemanticsof

/orders‒ItisusuallynotpossibletoperformupdatesontheseresourcesNon-composedresourcesusestrongETags‒Forexample/orders/{order-id}‒TheycanbeupdatedFurthernotes‒ServershouldsendbothLast-ModifiedandETagheaders‒IfclientsendsbothIf-Modified-SinceandIf-None-Match,ETagvalidationtakespreference

Lecture4:HATEOAS,CachingandConcurrency,CTUWinterSemester2021/2022,@TomasVitvar ‒19‒

Page 20: Middleware Architectures 1

WeakETagExampleAppspecific,/ordersresourceexample

WeakETagcomputefunctionexample‒Anymodificationtoanorder'sitemsisnotsignificantfor/orders:

12345678910111213

{"orders":[{"id":2245,"customer":"Tomas","descr":"Stufftobuildahouse.","items":[...]},{"id":5546,"customer":"Peter","descr":"Thingstobuildapipeline.","items":[...]}]}

12345678

varcrypto=require("crypto");functioncomputeWeakETag(orders){varcontent="";for(vari=0;i<orders.length;i++)content+=orders[i].id+orders[i].customer+orders[i].descr;returncrypto.createHash('md5').update(content).digest("hex");}

Lecture4:HATEOAS,CachingandConcurrency,CTUWinterSemester2021/2022,@TomasVitvar ‒20‒

Page 21: Middleware Architectures 1

WeakETagRevalidationUpdating/ordersresource‒POST/orders/{order-id}insertsanewitemtoanorder‒Anychangestoorders'itemswillnotchangetheWeakETag

Lecture4:HATEOAS,CachingandConcurrency,CTUWinterSemester2021/2022,@TomasVitvar ‒21‒

Page 22: Middleware Architectures 1

ConcurrencyTwoclientsmayupdatethesameresource1)aclientGETsaresourceGET/orders/55452)theclientmodifiestheresource3)theclientupdatestheresourceviaPUT/orders/5545HTTP/1.1

Whathappensifanotherclientupdatestheresourcebetween1)and3)?Concurrencycontrol‒ConditionalPUT→UpdatetheresourceonlyifithasnotchangedsinceaspecifieddateoraspecifiedETagmatchestheresourcecontent

‒If-Unmodified-SinceandIf-Matchheaders‒ResponsetoconditionalPUT:→200OKifthePUTwassuccessful→412PreconditionFailediftheresourcewasupdatedinthemeantime.

Lecture4:HATEOAS,CachingandConcurrency,CTUWinterSemester2021/2022,@TomasVitvar ‒22‒

Page 23: Middleware Architectures 1

ConcurrencyControlProtocol

ConditionalPUTandETags‒ConditionalPUTmustalwaysusestrongentitytagsordatevalidation

Lecture4:HATEOAS,CachingandConcurrency,CTUWinterSemester2021/2022,@TomasVitvar ‒23‒

Page 24: Middleware Architectures 1

Overview

HATEOASCaching,Revalidation,ConcurrencyControlRichardsonMaturiyModel

Lecture4:HATEOAS,CachingandConcurrency,CTUWinterSemester2021/2022,@TomasVitvar ‒24‒

Page 25: Middleware Architectures 1

StepstowardsREST

SeeRichardsonMaturiyModeldetails.

Lecture4:HATEOAS,CachingandConcurrency,CTUWinterSemester2021/2022,@TomasVitvar ‒25‒

Page 26: Middleware Architectures 1

LevelsLEVEL0–POX(PlainOldXML)‒HTTPasatunnelingmechanism‒URLdefinesaserviceendpoint‒NoWebprinciplesLEVEL1–Resources‒TakeadvantagesofresourcesandURIsLEVEL2–HTTPVerbs‒UseHTTPmethodsandrespecttheirsemanticsLEVEL3–HypermediaControls‒HATEOAS

Lecture4:HATEOAS,CachingandConcurrency,CTUWinterSemester2021/2022,@TomasVitvar ‒26‒