-
Notifications
You must be signed in to change notification settings - Fork 1.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
MemoryArtifactStore for unit testing and ArtifactStore SPI Validation #3517
Merged
Merged
Changes from 1 commit
Commits
Show all changes
37 commits
Select commit
Hold shift + click to select a range
9b2b0ce
Initial implementation of MemoryArtifactStore
chetanmeh fe7692c
Create Read and Delete support completed
chetanmeh 0def54c
Add DocumentHandler tests
chetanmeh e4c7056
Initial query support
chetanmeh 9f47647
Implement query support for activations
chetanmeh ef97eff
Implement count support
chetanmeh 9e5b5fa
Make tests modular
chetanmeh afe61d8
Move MemoryArtifactStore to common/scala from tests
chetanmeh 16d709d
Remove support for "all" view
chetanmeh a587a5d
Switch to DocId instead of simple String id
chetanmeh cdd96b3
Refactor deserialization logic to utility method
chetanmeh 3cb4d25
Initial support for subjects/identities view queries
chetanmeh 033bec5
Test to validate subject limits support
chetanmeh d67145c
Remove test for "all" view
chetanmeh 78a2d57
Change behavior to match CouchDBRestStore
chetanmeh 87d28cc
Make EntityName creation random
chetanmeh 48f73ac
Make TCK run against CouchDB
chetanmeh b4dbf69
Add check for supported view names
chetanmeh e828966
Test to check blocked subject handling
chetanmeh b03b323
Test to check blocked subject handling
chetanmeh 5a3566a
Test to confirm that query response for subject matches CouchDB format
chetanmeh 4e2204a
Make transformViewResult return an Option[JsObject]
chetanmeh 419ee02
Add support for blacklisted namespace view
chetanmeh afaf4ad
Remove unused method
chetanmeh 4fbaa57
Implement basic attachment handling support
chetanmeh e5d5969
Fix the view name
chetanmeh 57b6d0b
Add test and support for querying public packages
chetanmeh 8199238
Remove new activationStore instance
chetanmeh 75df4c6
Make test abort if they cannot be run with MemoryArtifactStore
chetanmeh 0ba3b29
Refer to view names from entity objects
chetanmeh 3babc0a
Minor code touchup
chetanmeh c2b48ca
Assume should be called from within withFixture and not in before
chetanmeh 97c83a6
Add test to assert the query involving since and untill
chetanmeh 0f20838
Make test extend FlatSpec directly
chetanmeh c58c6c5
Add scala docs
chetanmeh 095eebd
Refactor to use the common deserialization utility method
chetanmeh 710aca5
Add test to check del with revision check
chetanmeh File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next
Next commit
Initial implementation of MemoryArtifactStore
commit 9b2b0ce01854b78acb1c2416f26828d782912d7a
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
372 changes: 372 additions & 0 deletions
372
common/scala/src/main/scala/whisk/core/database/DocumentHandler.scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,372 @@ | ||
/* | ||
* Licensed to the Apache Software Foundation (ASF) under one or more | ||
* contributor license agreements. See the NOTICE file distributed with | ||
* this work for additional information regarding copyright ownership. | ||
* The ASF licenses this file to You under the Apache License, Version 2.0 | ||
* (the "License"); you may not use this file except in compliance with | ||
* the License. You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
package whisk.core.database | ||
|
||
import spray.json._ | ||
import spray.json.DefaultJsonProtocol._ | ||
import whisk.common.TransactionId | ||
import whisk.core.entity.EntityPath.PATHSEP | ||
import whisk.utils.JsHelpers | ||
|
||
import scala.concurrent.Future | ||
import scala.concurrent.ExecutionContext | ||
|
||
/** | ||
* Simple abstraction allow accessing a document just by _id. This would be used | ||
* to perform queries related to join support | ||
*/ | ||
trait DocumentProvider { | ||
protected[database] def get(id: String)(implicit transid: TransactionId): Future[JsObject] | ||
} | ||
|
||
trait DocumentHandler { | ||
|
||
/** | ||
* Returns a JsObject having computed fields. This is a substitution for fields | ||
* computed in CouchDB views | ||
*/ | ||
def computedFields(js: JsObject): JsObject = JsObject.empty | ||
|
||
def fieldsRequiredForView(ddoc: String, view: String): Set[String] = Set() | ||
|
||
def transformViewResult( | ||
ddoc: String, | ||
view: String, | ||
startKey: List[Any], | ||
endKey: List[Any], | ||
includeDocs: Boolean, | ||
js: JsObject, | ||
provider: DocumentProvider)(implicit transid: TransactionId, ec: ExecutionContext): Future[JsObject] | ||
|
||
def shouldAlwaysIncludeDocs(ddoc: String, view: String): Boolean = false | ||
} | ||
|
||
/** | ||
* Base class for handlers which do not perform joins for computing views | ||
*/ | ||
abstract class SimpleHandler extends DocumentHandler { | ||
override def transformViewResult( | ||
ddoc: String, | ||
view: String, | ||
startKey: List[Any], | ||
endKey: List[Any], | ||
includeDocs: Boolean, | ||
js: JsObject, | ||
provider: DocumentProvider)(implicit transid: TransactionId, ec: ExecutionContext): Future[JsObject] = { | ||
val viewResult = JsObject( | ||
"id" -> js.fields("_id"), | ||
"key" -> createKey(ddoc, view, startKey, js), | ||
"value" -> computeView(ddoc, view, js)) | ||
|
||
val result = if (includeDocs) JsObject(viewResult.fields + ("doc" -> js)) else viewResult | ||
Future.successful(result) | ||
} | ||
|
||
/** | ||
* Computes the view as per viewName. Its passed either the projected object or actual | ||
* object | ||
*/ | ||
def computeView(ddoc: String, view: String, js: JsObject): JsObject | ||
|
||
/** | ||
* Key is an array which matches the view query key | ||
*/ | ||
protected def createKey(ddoc: String, view: String, startKey: List[Any], js: JsObject): JsArray | ||
} | ||
|
||
object ActivationHandler extends SimpleHandler { | ||
val NS_PATH = "nspath" | ||
private val commonFields = | ||
Set("namespace", "name", "version", "publish", "annotations", "activationId", "start", "cause") | ||
private val fieldsForView = commonFields ++ Seq("end", "response.statusCode") | ||
|
||
override def computedFields(js: JsObject): JsObject = { | ||
val path = js.fields.get("namespace") match { | ||
case Some(JsString(namespace)) => JsString(namespace + PATHSEP + pathFilter(js)) | ||
case _ => JsNull | ||
} | ||
val deleteLogs = annotationValue(js, "kind", { v => | ||
v.convertTo[String] != "sequence" | ||
}, true) | ||
dropNull((NS_PATH, path), ("deleteLogs", JsBoolean(deleteLogs))) | ||
} | ||
|
||
override def fieldsRequiredForView(ddoc: String, view: String): Set[String] = view match { | ||
case "activations" => fieldsForView | ||
case _ => throw UnsupportedView(s"$ddoc/$view") | ||
} | ||
|
||
def computeView(ddoc: String, view: String, js: JsObject): JsObject = view match { | ||
case "activations" => computeActivationView(js) | ||
case _ => throw UnsupportedView(s"$ddoc/$view") | ||
} | ||
|
||
def createKey(ddoc: String, view: String, startKey: List[Any], js: JsObject): JsArray = { | ||
startKey match { | ||
case (ns: String) :: Nil => JsArray(Vector(JsString(ns))) | ||
case (ns: String) :: _ :: Nil => JsArray(Vector(JsString(ns), js.fields("start"))) | ||
case _ => throw UnsupportedQueryKeys("$ddoc/$view -> ($startKey, $endKey)") | ||
} | ||
} | ||
|
||
private def computeActivationView(js: JsObject): JsObject = { | ||
val common = js.fields.filterKeys(commonFields) | ||
|
||
val (endTime, duration) = js.getFields("end", "start") match { | ||
case Seq(JsNumber(end), JsNumber(start)) if end != 0 => (JsNumber(end), JsNumber(end - start)) | ||
case _ => (JsNull, JsNull) | ||
} | ||
|
||
val statusCode = JsHelpers.getFieldPath(js, "response", "statusCode").getOrElse(JsNull) | ||
|
||
val result = common + ("end" -> endTime) + ("duration" -> duration) + ("statusCode" -> statusCode) | ||
JsObject(result.filter(_._2 != JsNull)) | ||
} | ||
|
||
protected[database] def pathFilter(js: JsObject): String = { | ||
val name = js.fields("name").convertTo[String] | ||
annotationValue(js, "path", { v => | ||
val p = v.convertTo[String].split(PATHSEP) | ||
if (p.length == 3) p(1) + PATHSEP + name else name | ||
}, name) | ||
} | ||
|
||
/** | ||
* Finds and transforms annotation with matching key. | ||
* | ||
* @param js js object having annotations array | ||
* @param key annotation key | ||
* @param vtr transformer function to map annotation value | ||
* @param default default value to use if no matching annotation found | ||
* @return annotation value matching given key | ||
*/ | ||
protected[database] def annotationValue[T](js: JsObject, key: String, vtr: JsValue => T, default: T): T = { | ||
js.fields.get("annotations") match { | ||
case Some(JsArray(e)) => | ||
e.view | ||
.map(_.asJsObject.getFields("key", "value")) | ||
.collectFirst { | ||
case Seq(JsString(`key`), v: JsValue) => vtr(v) //match annotation with given key | ||
} | ||
.getOrElse(default) | ||
case _ => default | ||
} | ||
} | ||
|
||
private def dropNull(fields: JsField*) = JsObject(fields.filter(_._2 != JsNull): _*) | ||
} | ||
|
||
object WhisksHandler extends SimpleHandler { | ||
val ROOT_NS = "rootns" | ||
private val commonFields = Set("namespace", "name", "version", "publish", "annotations", "updated") | ||
private val actionFields = commonFields ++ Set("limits", "exec.binary") | ||
private val packageFields = commonFields ++ Set("binding") | ||
private val packagePublicFields = commonFields | ||
private val ruleFields = commonFields | ||
private val triggerFields = commonFields | ||
private val allFields = commonFields ++ actionFields ++ packageFields ++ packagePublicFields ++ ruleFields ++ triggerFields ++ Seq( | ||
"entityType") | ||
|
||
override def computedFields(js: JsObject): JsObject = { | ||
js.fields.get("namespace") match { | ||
case Some(JsString(namespace)) => | ||
val ns = namespace.split(PATHSEP) | ||
val rootNS = if (ns.length > 1) ns(0) else namespace | ||
JsObject((ROOT_NS, JsString(rootNS))) | ||
case _ => JsObject.empty | ||
} | ||
} | ||
|
||
override def fieldsRequiredForView(ddoc: String, view: String): Set[String] = view match { | ||
case "actions" => actionFields | ||
case "packages" => packageFields | ||
case "packages-public" => packagePublicFields | ||
case "rules" => ruleFields | ||
case "triggers" => triggerFields | ||
case "all" => allFields | ||
case _ => throw UnsupportedView(s"$ddoc/$view") | ||
} | ||
|
||
def computeView(ddoc: String, view: String, js: JsObject): JsObject = view match { | ||
case "actions" => computeActionView(js) | ||
case "packages" => computePackageView(js) | ||
case "packages-public" => computePublicPackageView(js) | ||
case "rules" => computeRulesView(js) | ||
case "triggers" => computeTriggersView(js) | ||
case "all" => computeAllView(js) | ||
case _ => throw UnsupportedView(s"$ddoc/$view") | ||
} | ||
|
||
def createKey(ddoc: String, view: String, startKey: List[Any], js: JsObject): JsArray = { | ||
startKey match { | ||
case (ns: String) :: Nil => JsArray(Vector(JsString(ns))) | ||
case (ns: String) :: _ :: Nil => JsArray(Vector(JsString(ns), js.fields("updated"))) | ||
case _ => throw UnsupportedQueryKeys("$ddoc/$view -> ($startKey, $endKey)") | ||
} | ||
} | ||
|
||
private def computeTriggersView(js: JsObject): JsObject = { | ||
JsObject(js.fields.filterKeys(commonFields)) | ||
} | ||
|
||
private def computePublicPackageView(js: JsObject): JsObject = { | ||
JsObject(js.fields.filterKeys(commonFields) + ("binding" -> JsFalse)) | ||
} | ||
|
||
private def computeRulesView(js: JsObject) = { | ||
JsObject(js.fields.filterKeys(ruleFields)) | ||
} | ||
|
||
private def computePackageView(js: JsObject): JsObject = { | ||
val common = js.fields.filterKeys(commonFields) | ||
val binding = js.fields.get("binding") match { | ||
case Some(x: JsObject) if x.fields.nonEmpty => x | ||
case _ => JsFalse | ||
} | ||
JsObject(common + ("binding" -> binding)) | ||
} | ||
|
||
private def computeActionView(js: JsObject): JsObject = { | ||
val base = js.fields.filterKeys(commonFields ++ Set("limits")) | ||
val exec_binary = JsHelpers.getFieldPath(js, "exec", "binary") | ||
JsObject(base + ("exec" -> JsObject("binary" -> exec_binary.getOrElse(JsFalse)))) | ||
} | ||
|
||
private def computeAllView(js: JsObject): JsObject = { | ||
val collection = js.fields("entityType").convertTo[String] | ||
val computed = collection match { | ||
case "action" => computeActionView(js) | ||
case "package" => computePackageView(js) | ||
case "rule" => computeRulesView(js) | ||
case "trigger" => computeTriggersView(js) | ||
} | ||
JsObject(computed.fields + ("collection" -> JsString(collection))) | ||
} | ||
} | ||
|
||
object SubjectHandler extends DocumentHandler { | ||
|
||
override def shouldAlwaysIncludeDocs(ddoc: String, view: String): Boolean = { | ||
checkSupportedView(ddoc, view) | ||
true | ||
} | ||
|
||
override def transformViewResult( | ||
ddoc: String, | ||
view: String, | ||
startKey: List[Any], | ||
endKey: List[Any], | ||
includeDocs: Boolean, | ||
js: JsObject, | ||
provider: DocumentProvider)(implicit transid: TransactionId, ec: ExecutionContext): Future[JsObject] = { | ||
require(includeDocs) //For subject/identities includeDocs is always true | ||
|
||
val subject = computeSubjectView(ddoc, view, startKey, js) | ||
val viewJS = JsObject( | ||
"namespace" -> JsString(subject.namespace), | ||
"uuid" -> JsString(subject.uuid), | ||
"key" -> JsString(subject.key)) | ||
val result = | ||
JsObject("id" -> js.fields("_id"), "key" -> createKey(ddoc, view, startKey), "value" -> viewJS, "doc" -> JsNull) | ||
if (subject.matchInNamespace) { | ||
val limitDocId = s"${subject.namespace}/limits" | ||
provider.get(limitDocId).map(limits => JsObject(result.fields + ("doc" -> limits))) | ||
} else { | ||
Future.successful(result) | ||
} | ||
} | ||
|
||
def checkSupportedView(ddoc: String, view: String): Unit = { | ||
if (ddoc != "subjects" || view != "identities") { | ||
throw UnsupportedView(s"$ddoc/$view") | ||
} | ||
} | ||
|
||
def computeSubjectView(ddoc: String, view: String, startKey: List[Any], js: JsObject): SubjectView = { | ||
val viewJs = startKey match { | ||
case (ns: String) :: Nil => findMatchingSubject(js, s => s.namespace == ns && !s.blocked) | ||
case (uuid: String) :: (key: String) :: Nil => | ||
findMatchingSubject(js, s => s.uuid == uuid && s.key == key && !s.blocked) | ||
case _ => None | ||
} | ||
viewJs.getOrElse(throw new IllegalArgumentException(s"Subject does not match ${startKey.head}")) | ||
} | ||
|
||
private def createKey(ddoc: String, view: String, startKey: List[Any]): JsArray = { | ||
startKey match { | ||
case (ns: String) :: Nil => JsArray(Vector(JsString(ns))) //namespace or subject | ||
case (uuid: String) :: (key: String) :: Nil => JsArray(Vector(JsString(uuid), JsString(key))) // uuid, key | ||
case _ => throw UnsupportedQueryKeys("$ddoc/$view -> ($startKey, $endKey)") | ||
} | ||
} | ||
|
||
/** | ||
* Computes the view as per logic below from (identities/subject) view | ||
* | ||
* {{{ | ||
* function (doc) { | ||
* if(doc.uuid && doc.key && !doc.blocked) { | ||
* var v = {namespace: doc.subject, uuid: doc.uuid, key: doc.key}; | ||
* emit([doc.subject], v); | ||
* emit([doc.uuid, doc.key], v); | ||
* } | ||
* if(doc.namespaces && !doc.blocked) { | ||
* doc.namespaces.forEach(function(namespace) { | ||
* var v = {_id: namespace.name + '/limits', namespace: namespace.name, uuid: namespace.uuid, key: namespace.key}; | ||
* emit([namespace.name], v); | ||
* emit([namespace.uuid, namespace.key], v); | ||
* }); | ||
* } | ||
* } | ||
* }}} | ||
* | ||
* @param js subject json from db | ||
* @param matches match predicate | ||
*/ | ||
private def findMatchingSubject(js: JsObject, matches: SubjectView => Boolean): Option[SubjectView] = { | ||
val blocked = js.fields.get("blocked") match { | ||
case Some(JsTrue) => true | ||
case _ => false | ||
} | ||
|
||
val r = js.getFields("subject", "uuid", "key") match { | ||
case Seq(JsString(ns), JsString(uuid), JsString(key)) => Some(SubjectView(ns, uuid, key, blocked)).filter(matches) | ||
case _ => None | ||
} | ||
|
||
r.orElse { | ||
val namespaces = js.fields.get("namespaces") match { | ||
case Some(JsArray(e)) => | ||
e.map(_.asJsObject.getFields("name", "uuid", "key") match { | ||
case Seq(JsString(ns), JsString(uuid), JsString(key)) => | ||
Some(SubjectView(ns, uuid, key, blocked, matchInNamespace = true)) | ||
case _ => None | ||
}) | ||
|
||
case _ => Seq() | ||
} | ||
namespaces.flatMap(_.filter(matches)).headOption | ||
} | ||
} | ||
|
||
case class SubjectView(namespace: String, | ||
uuid: String, | ||
key: String, | ||
blocked: Boolean = false, | ||
matchInNamespace: Boolean = false) | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Is this sealed class intended to restrict exceptions for views only vs documents?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Made it
sealed
to follow the pattern used withArtifactStoreException
i.e. a baseRuntimeException
which can be used to indicate logical errors in code flow. So can be used for both views and document