Page MenuHomestyx hydra

No OneTemporary

diff --git a/src/applications/herald/adapter/HeraldAdapter.php b/src/applications/herald/adapter/HeraldAdapter.php
index 69f538afcc..cb8545b71d 100644
--- a/src/applications/herald/adapter/HeraldAdapter.php
+++ b/src/applications/herald/adapter/HeraldAdapter.php
@@ -1,1247 +1,1255 @@
<?php
abstract class HeraldAdapter extends Phobject {
const CONDITION_CONTAINS = 'contains';
const CONDITION_NOT_CONTAINS = '!contains';
const CONDITION_IS = 'is';
const CONDITION_IS_NOT = '!is';
const CONDITION_IS_ANY = 'isany';
const CONDITION_IS_NOT_ANY = '!isany';
const CONDITION_INCLUDE_ALL = 'all';
const CONDITION_INCLUDE_ANY = 'any';
const CONDITION_INCLUDE_NONE = 'none';
const CONDITION_IS_ME = 'me';
const CONDITION_IS_NOT_ME = '!me';
const CONDITION_REGEXP = 'regexp';
const CONDITION_NOT_REGEXP = '!regexp';
const CONDITION_RULE = 'conditions';
const CONDITION_NOT_RULE = '!conditions';
const CONDITION_EXISTS = 'exists';
const CONDITION_NOT_EXISTS = '!exists';
const CONDITION_UNCONDITIONALLY = 'unconditionally';
const CONDITION_NEVER = 'never';
const CONDITION_REGEXP_PAIR = 'regexp-pair';
const CONDITION_HAS_BIT = 'bit';
const CONDITION_NOT_BIT = '!bit';
const CONDITION_IS_TRUE = 'true';
const CONDITION_IS_FALSE = 'false';
private $contentSource;
private $isNewObject;
private $applicationEmail;
private $appliedTransactions = array();
private $queuedTransactions = array();
private $emailPHIDs = array();
private $forcedEmailPHIDs = array();
private $fieldMap;
private $actionMap;
private $edgeCache = array();
private $forbiddenActions = array();
private $viewer;
private $mustEncryptReasons = array();
private $actingAsPHID;
private $webhookMap = array();
public function getEmailPHIDs() {
return array_values($this->emailPHIDs);
}
public function getForcedEmailPHIDs() {
return array_values($this->forcedEmailPHIDs);
}
final public function setActingAsPHID($acting_as_phid) {
$this->actingAsPHID = $acting_as_phid;
return $this;
}
final public function getActingAsPHID() {
return $this->actingAsPHID;
}
public function addEmailPHID($phid, $force) {
$this->emailPHIDs[$phid] = $phid;
if ($force) {
$this->forcedEmailPHIDs[$phid] = $phid;
}
return $this;
}
public function setViewer(PhabricatorUser $viewer) {
$this->viewer = $viewer;
return $this;
}
public function getViewer() {
// See PHI276. Normally, Herald runs without regard for policy checks.
// However, we use a real viewer during test console runs: this makes
// intracluster calls to Diffusion APIs work even if web nodes don't
// have privileged credentials.
if ($this->viewer) {
return $this->viewer;
}
return PhabricatorUser::getOmnipotentUser();
}
public function setContentSource(PhabricatorContentSource $content_source) {
$this->contentSource = $content_source;
return $this;
}
public function getContentSource() {
return $this->contentSource;
}
public function getIsNewObject() {
if (is_bool($this->isNewObject)) {
return $this->isNewObject;
}
throw new Exception(
pht(
'You must %s to a boolean first!',
'setIsNewObject()'));
}
public function setIsNewObject($new) {
$this->isNewObject = (bool)$new;
return $this;
}
public function supportsApplicationEmail() {
return false;
}
public function setApplicationEmail(
PhabricatorMetaMTAApplicationEmail $email) {
$this->applicationEmail = $email;
return $this;
}
public function getApplicationEmail() {
return $this->applicationEmail;
}
public function getPHID() {
return $this->getObject()->getPHID();
}
abstract public function getHeraldName();
+ final public function willGetHeraldField($field_key) {
+ // This method is called during rule evaluation, before we engage the
+ // Herald profiler. We make sure we have a concrete implementation so time
+ // spent loading fields out of the classmap is not mistakenly attributed to
+ // whichever field happens to evaluate first.
+ $this->requireFieldImplementation($field_key);
+ }
+
public function getHeraldField($field_key) {
return $this->requireFieldImplementation($field_key)
->getHeraldFieldValue($this->getObject());
}
public function applyHeraldEffects(array $effects) {
assert_instances_of($effects, 'HeraldEffect');
$result = array();
foreach ($effects as $effect) {
$result[] = $this->applyStandardEffect($effect);
}
return $result;
}
public function isAvailableToUser(PhabricatorUser $viewer) {
$applications = id(new PhabricatorApplicationQuery())
->setViewer($viewer)
->withInstalled(true)
->withClasses(array($this->getAdapterApplicationClass()))
->execute();
return !empty($applications);
}
/**
* Set the list of transactions which just took effect.
*
* These transactions are set by @{class:PhabricatorApplicationEditor}
* automatically, before it invokes Herald.
*
* @param list<PhabricatorApplicationTransaction> List of transactions.
* @return this
*/
final public function setAppliedTransactions(array $xactions) {
assert_instances_of($xactions, 'PhabricatorApplicationTransaction');
$this->appliedTransactions = $xactions;
return $this;
}
/**
* Get a list of transactions which just took effect.
*
* When an object is edited normally, transactions are applied and then
* Herald executes. You can call this method to examine the transactions
* if you want to react to them.
*
* @return list<PhabricatorApplicationTransaction> List of transactions.
*/
final public function getAppliedTransactions() {
return $this->appliedTransactions;
}
final public function queueTransaction(
PhabricatorApplicationTransaction $transaction) {
$this->queuedTransactions[] = $transaction;
}
final public function getQueuedTransactions() {
return $this->queuedTransactions;
}
final public function newTransaction() {
$object = $this->newObject();
if (!($object instanceof PhabricatorApplicationTransactionInterface)) {
throw new Exception(
pht(
'Unable to build a new transaction for adapter object; it does '.
'not implement "%s".',
'PhabricatorApplicationTransactionInterface'));
}
$xaction = $object->getApplicationTransactionTemplate();
if (!($xaction instanceof PhabricatorApplicationTransaction)) {
throw new Exception(
pht(
'Expected object (of class "%s") to return a transaction template '.
'(of class "%s"), but it returned something else ("%s").',
get_class($object),
'PhabricatorApplicationTransaction',
phutil_describe_type($xaction)));
}
return $xaction;
}
/**
* NOTE: You generally should not override this; it exists to support legacy
* adapters which had hard-coded content types.
*/
public function getAdapterContentType() {
return get_class($this);
}
abstract public function getAdapterContentName();
abstract public function getAdapterContentDescription();
abstract public function getAdapterApplicationClass();
abstract public function getObject();
/**
* Return a new characteristic object for this adapter.
*
* The adapter will use this object to test for interfaces, generate
* transactions, and interact with custom fields.
*
* Adapters must return an object from this method to enable custom
* field rules and various implicit actions.
*
* Normally, you'll return an empty version of the adapted object:
*
* return new ApplicationObject();
*
* @return null|object Template object.
*/
protected function newObject() {
return null;
}
public function supportsRuleType($rule_type) {
return false;
}
public function canTriggerOnObject($object) {
return false;
}
public function isTestAdapterForObject($object) {
return false;
}
public function canCreateTestAdapterForObject($object) {
return $this->isTestAdapterForObject($object);
}
public function newTestAdapter(PhabricatorUser $viewer, $object) {
return id(clone $this)
->setObject($object);
}
public function getAdapterTestDescription() {
return null;
}
public function explainValidTriggerObjects() {
return pht('This adapter can not trigger on objects.');
}
public function getTriggerObjectPHIDs() {
return array($this->getPHID());
}
public function getAdapterSortKey() {
return sprintf(
'%08d%s',
$this->getAdapterSortOrder(),
$this->getAdapterContentName());
}
public function getAdapterSortOrder() {
return 1000;
}
/* -( Fields )------------------------------------------------------------- */
private function getFieldImplementationMap() {
if ($this->fieldMap === null) {
// We can't use PhutilClassMapQuery here because field expansion
// depends on the adapter and object.
$object = $this->getObject();
$map = array();
$all = HeraldField::getAllFields();
foreach ($all as $key => $field) {
$field = id(clone $field)->setAdapter($this);
if (!$field->supportsObject($object)) {
continue;
}
$subfields = $field->getFieldsForObject($object);
foreach ($subfields as $subkey => $subfield) {
if (isset($map[$subkey])) {
throw new Exception(
pht(
'Two HeraldFields (of classes "%s" and "%s") have the same '.
'field key ("%s") after expansion for an object of class '.
'"%s" inside adapter "%s". Each field must have a unique '.
'field key.',
get_class($subfield),
get_class($map[$subkey]),
$subkey,
get_class($object),
get_class($this)));
}
$subfield = id(clone $subfield)->setAdapter($this);
$map[$subkey] = $subfield;
}
}
$this->fieldMap = $map;
}
return $this->fieldMap;
}
private function getFieldImplementation($key) {
return idx($this->getFieldImplementationMap(), $key);
}
public function getFields() {
return array_keys($this->getFieldImplementationMap());
}
public function getFieldNameMap() {
return mpull($this->getFieldImplementationMap(), 'getHeraldFieldName');
}
public function getFieldGroupKey($field_key) {
$field = $this->getFieldImplementation($field_key);
if (!$field) {
return null;
}
return $field->getFieldGroupKey();
}
/* -( Conditions )--------------------------------------------------------- */
public function getConditionNameMap() {
return array(
self::CONDITION_CONTAINS => pht('contains'),
self::CONDITION_NOT_CONTAINS => pht('does not contain'),
self::CONDITION_IS => pht('is'),
self::CONDITION_IS_NOT => pht('is not'),
self::CONDITION_IS_ANY => pht('is any of'),
self::CONDITION_IS_TRUE => pht('is true'),
self::CONDITION_IS_FALSE => pht('is false'),
self::CONDITION_IS_NOT_ANY => pht('is not any of'),
self::CONDITION_INCLUDE_ALL => pht('include all of'),
self::CONDITION_INCLUDE_ANY => pht('include any of'),
self::CONDITION_INCLUDE_NONE => pht('do not include'),
self::CONDITION_IS_ME => pht('is myself'),
self::CONDITION_IS_NOT_ME => pht('is not myself'),
self::CONDITION_REGEXP => pht('matches regexp'),
self::CONDITION_NOT_REGEXP => pht('does not match regexp'),
self::CONDITION_RULE => pht('matches:'),
self::CONDITION_NOT_RULE => pht('does not match:'),
self::CONDITION_EXISTS => pht('exists'),
self::CONDITION_NOT_EXISTS => pht('does not exist'),
self::CONDITION_UNCONDITIONALLY => '', // don't show anything!
self::CONDITION_NEVER => '', // don't show anything!
self::CONDITION_REGEXP_PAIR => pht('matches regexp pair'),
self::CONDITION_HAS_BIT => pht('has bit'),
self::CONDITION_NOT_BIT => pht('lacks bit'),
);
}
public function getConditionsForField($field) {
return $this->requireFieldImplementation($field)
->getHeraldFieldConditions();
}
private function requireFieldImplementation($field_key) {
$field = $this->getFieldImplementation($field_key);
if (!$field) {
throw new Exception(
pht(
'No field with key "%s" is available to Herald adapter "%s".',
$field_key,
get_class($this)));
}
return $field;
}
public function doesConditionMatch(
HeraldEngine $engine,
HeraldRule $rule,
HeraldCondition $condition,
$field_value) {
$condition_type = $condition->getFieldCondition();
$condition_value = $condition->getValue();
switch ($condition_type) {
case self::CONDITION_CONTAINS:
case self::CONDITION_NOT_CONTAINS:
// "Contains and "does not contain" can take an array of strings, as in
// "Any changed filename" for diffs.
$result_if_match = ($condition_type == self::CONDITION_CONTAINS);
foreach ((array)$field_value as $value) {
if (stripos($value, $condition_value) !== false) {
return $result_if_match;
}
}
return !$result_if_match;
case self::CONDITION_IS:
return ($field_value == $condition_value);
case self::CONDITION_IS_NOT:
return ($field_value != $condition_value);
case self::CONDITION_IS_ME:
return ($field_value == $rule->getAuthorPHID());
case self::CONDITION_IS_NOT_ME:
return ($field_value != $rule->getAuthorPHID());
case self::CONDITION_IS_ANY:
if (!is_array($condition_value)) {
throw new HeraldInvalidConditionException(
pht('Expected condition value to be an array.'));
}
$condition_value = array_fuse($condition_value);
return isset($condition_value[$field_value]);
case self::CONDITION_IS_NOT_ANY:
if (!is_array($condition_value)) {
throw new HeraldInvalidConditionException(
pht('Expected condition value to be an array.'));
}
$condition_value = array_fuse($condition_value);
return !isset($condition_value[$field_value]);
case self::CONDITION_INCLUDE_ALL:
if (!is_array($field_value)) {
throw new HeraldInvalidConditionException(
pht('Object produced non-array value!'));
}
if (!is_array($condition_value)) {
throw new HeraldInvalidConditionException(
pht('Expected condition value to be an array.'));
}
$have = array_select_keys(array_fuse($field_value), $condition_value);
return (count($have) == count($condition_value));
case self::CONDITION_INCLUDE_ANY:
return (bool)array_select_keys(
array_fuse($field_value),
$condition_value);
case self::CONDITION_INCLUDE_NONE:
return !array_select_keys(
array_fuse($field_value),
$condition_value);
case self::CONDITION_EXISTS:
case self::CONDITION_IS_TRUE:
return (bool)$field_value;
case self::CONDITION_NOT_EXISTS:
case self::CONDITION_IS_FALSE:
return !$field_value;
case self::CONDITION_UNCONDITIONALLY:
return (bool)$field_value;
case self::CONDITION_NEVER:
return false;
case self::CONDITION_REGEXP:
case self::CONDITION_NOT_REGEXP:
$result_if_match = ($condition_type == self::CONDITION_REGEXP);
foreach ((array)$field_value as $value) {
// We add the 'S' flag because we use the regexp multiple times.
// It shouldn't cause any troubles if the flag is already there
// - /.*/S is evaluated same as /.*/SS.
$result = @preg_match($condition_value.'S', $value);
if ($result === false) {
throw new HeraldInvalidConditionException(
pht(
'Regular expression "%s" in Herald rule "%s" is not valid, '.
'or exceeded backtracking or recursion limits while '.
'executing. Verify the expression and correct it or rewrite '.
'it with less backtracking.',
$condition_value,
$rule->getMonogram()));
}
if ($result) {
return $result_if_match;
}
}
return !$result_if_match;
case self::CONDITION_REGEXP_PAIR:
// Match a JSON-encoded pair of regular expressions against a
// dictionary. The first regexp must match the dictionary key, and the
// second regexp must match the dictionary value. If any key/value pair
// in the dictionary matches both regexps, the condition is satisfied.
$regexp_pair = null;
try {
$regexp_pair = phutil_json_decode($condition_value);
} catch (PhutilJSONParserException $ex) {
throw new HeraldInvalidConditionException(
pht('Regular expression pair is not valid JSON!'));
}
if (count($regexp_pair) != 2) {
throw new HeraldInvalidConditionException(
pht('Regular expression pair is not a pair!'));
}
$key_regexp = array_shift($regexp_pair);
$value_regexp = array_shift($regexp_pair);
foreach ((array)$field_value as $key => $value) {
$key_matches = @preg_match($key_regexp, $key);
if ($key_matches === false) {
throw new HeraldInvalidConditionException(
pht('First regular expression is invalid!'));
}
if ($key_matches) {
$value_matches = @preg_match($value_regexp, $value);
if ($value_matches === false) {
throw new HeraldInvalidConditionException(
pht('Second regular expression is invalid!'));
}
if ($value_matches) {
return true;
}
}
}
return false;
case self::CONDITION_RULE:
case self::CONDITION_NOT_RULE:
$rule = $engine->getRule($condition_value);
if (!$rule) {
throw new HeraldInvalidConditionException(
pht('Condition references a rule which does not exist!'));
}
$is_not = ($condition_type == self::CONDITION_NOT_RULE);
$result = $engine->doesRuleMatch($rule, $this);
if ($is_not) {
$result = !$result;
}
return $result;
case self::CONDITION_HAS_BIT:
return (($condition_value & $field_value) === (int)$condition_value);
case self::CONDITION_NOT_BIT:
return (($condition_value & $field_value) !== (int)$condition_value);
default:
throw new HeraldInvalidConditionException(
pht("Unknown condition '%s'.", $condition_type));
}
}
public function willSaveCondition(HeraldCondition $condition) {
$condition_type = $condition->getFieldCondition();
$condition_value = $condition->getValue();
switch ($condition_type) {
case self::CONDITION_REGEXP:
case self::CONDITION_NOT_REGEXP:
$ok = @preg_match($condition_value, '');
if ($ok === false) {
throw new HeraldInvalidConditionException(
pht(
'The regular expression "%s" is not valid. Regular expressions '.
'must have enclosing characters (e.g. "@/path/to/file@", not '.
'"/path/to/file") and be syntactically correct.',
$condition_value));
}
break;
case self::CONDITION_REGEXP_PAIR:
$json = null;
try {
$json = phutil_json_decode($condition_value);
} catch (PhutilJSONParserException $ex) {
throw new HeraldInvalidConditionException(
pht(
'The regular expression pair "%s" is not valid JSON. Enter a '.
'valid JSON array with two elements.',
$condition_value));
}
if (count($json) != 2) {
throw new HeraldInvalidConditionException(
pht(
'The regular expression pair "%s" must have exactly two '.
'elements.',
$condition_value));
}
$key_regexp = array_shift($json);
$val_regexp = array_shift($json);
$key_ok = @preg_match($key_regexp, '');
if ($key_ok === false) {
throw new HeraldInvalidConditionException(
pht(
'The first regexp in the regexp pair, "%s", is not a valid '.
'regexp.',
$key_regexp));
}
$val_ok = @preg_match($val_regexp, '');
if ($val_ok === false) {
throw new HeraldInvalidConditionException(
pht(
'The second regexp in the regexp pair, "%s", is not a valid '.
'regexp.',
$val_regexp));
}
break;
case self::CONDITION_CONTAINS:
case self::CONDITION_NOT_CONTAINS:
case self::CONDITION_IS:
case self::CONDITION_IS_NOT:
case self::CONDITION_IS_ANY:
case self::CONDITION_IS_NOT_ANY:
case self::CONDITION_INCLUDE_ALL:
case self::CONDITION_INCLUDE_ANY:
case self::CONDITION_INCLUDE_NONE:
case self::CONDITION_IS_ME:
case self::CONDITION_IS_NOT_ME:
case self::CONDITION_RULE:
case self::CONDITION_NOT_RULE:
case self::CONDITION_EXISTS:
case self::CONDITION_NOT_EXISTS:
case self::CONDITION_UNCONDITIONALLY:
case self::CONDITION_NEVER:
case self::CONDITION_HAS_BIT:
case self::CONDITION_NOT_BIT:
case self::CONDITION_IS_TRUE:
case self::CONDITION_IS_FALSE:
// No explicit validation for these types, although there probably
// should be in some cases.
break;
default:
throw new HeraldInvalidConditionException(
pht(
'Unknown condition "%s"!',
$condition_type));
}
}
/* -( Actions )------------------------------------------------------------ */
private function getActionImplementationMap() {
if ($this->actionMap === null) {
// We can't use PhutilClassMapQuery here because action expansion
// depends on the adapter and object.
$object = $this->getObject();
$map = array();
$all = HeraldAction::getAllActions();
foreach ($all as $key => $action) {
$action = id(clone $action)->setAdapter($this);
if (!$action->supportsObject($object)) {
continue;
}
$subactions = $action->getActionsForObject($object);
foreach ($subactions as $subkey => $subaction) {
if (isset($map[$subkey])) {
throw new Exception(
pht(
'Two HeraldActions (of classes "%s" and "%s") have the same '.
'action key ("%s") after expansion for an object of class '.
'"%s" inside adapter "%s". Each action must have a unique '.
'action key.',
get_class($subaction),
get_class($map[$subkey]),
$subkey,
get_class($object),
get_class($this)));
}
$subaction = id(clone $subaction)->setAdapter($this);
$map[$subkey] = $subaction;
}
}
$this->actionMap = $map;
}
return $this->actionMap;
}
private function requireActionImplementation($action_key) {
$action = $this->getActionImplementation($action_key);
if (!$action) {
throw new Exception(
pht(
'No action with key "%s" is available to Herald adapter "%s".',
$action_key,
get_class($this)));
}
return $action;
}
private function getActionsForRuleType($rule_type) {
$actions = $this->getActionImplementationMap();
foreach ($actions as $key => $action) {
if (!$action->supportsRuleType($rule_type)) {
unset($actions[$key]);
}
}
return $actions;
}
public function getActionImplementation($key) {
return idx($this->getActionImplementationMap(), $key);
}
public function getActionKeys() {
return array_keys($this->getActionImplementationMap());
}
public function getActionGroupKey($action_key) {
$action = $this->getActionImplementation($action_key);
if (!$action) {
return null;
}
return $action->getActionGroupKey();
}
public function getActions($rule_type) {
$actions = array();
foreach ($this->getActionsForRuleType($rule_type) as $key => $action) {
$actions[] = $key;
}
return $actions;
}
public function getActionNameMap($rule_type) {
$map = array();
foreach ($this->getActionsForRuleType($rule_type) as $key => $action) {
$map[$key] = $action->getHeraldActionName();
}
return $map;
}
public function willSaveAction(
HeraldRule $rule,
HeraldActionRecord $action) {
$impl = $this->requireActionImplementation($action->getAction());
$target = $action->getTarget();
$target = $impl->willSaveActionValue($target);
$action->setTarget($target);
}
/* -( Values )------------------------------------------------------------- */
public function getValueTypeForFieldAndCondition($field, $condition) {
return $this->requireFieldImplementation($field)
->getHeraldFieldValueType($condition);
}
public function getValueTypeForAction($action, $rule_type) {
$impl = $this->requireActionImplementation($action);
return $impl->getHeraldActionValueType();
}
private function buildTokenizerFieldValue(
PhabricatorTypeaheadDatasource $datasource) {
$key = 'action.'.get_class($datasource);
return id(new HeraldTokenizerFieldValue())
->setKey($key)
->setDatasource($datasource);
}
/* -( Repetition )--------------------------------------------------------- */
public function getRepetitionOptions() {
$options = array();
$options[] = HeraldRule::REPEAT_EVERY;
// Some rules, like pre-commit rules, only ever fire once. It doesn't
// make sense to use state-based repetition policies like "only the first
// time" for these rules.
if (!$this->isSingleEventAdapter()) {
$options[] = HeraldRule::REPEAT_FIRST;
$options[] = HeraldRule::REPEAT_CHANGE;
}
return $options;
}
protected function initializeNewAdapter() {
$this->setObject($this->newObject());
return $this;
}
/**
* Does this adapter's event fire only once?
*
* Single use adapters (like pre-commit and diff adapters) only fire once,
* so fields like "Is new object" don't make sense to apply to their content.
*
* @return bool
*/
public function isSingleEventAdapter() {
return false;
}
public static function getAllAdapters() {
return id(new PhutilClassMapQuery())
->setAncestorClass(__CLASS__)
->setUniqueMethod('getAdapterContentType')
->setSortMethod('getAdapterSortKey')
->execute();
}
public static function getAdapterForContentType($content_type) {
$adapters = self::getAllAdapters();
foreach ($adapters as $adapter) {
if ($adapter->getAdapterContentType() == $content_type) {
$adapter = id(clone $adapter);
$adapter->initializeNewAdapter();
return $adapter;
}
}
throw new Exception(
pht(
'No adapter exists for Herald content type "%s".',
$content_type));
}
public static function getEnabledAdapterMap(PhabricatorUser $viewer) {
$map = array();
$adapters = self::getAllAdapters();
foreach ($adapters as $adapter) {
if (!$adapter->isAvailableToUser($viewer)) {
continue;
}
$type = $adapter->getAdapterContentType();
$name = $adapter->getAdapterContentName();
$map[$type] = $name;
}
return $map;
}
public function getEditorValueForCondition(
PhabricatorUser $viewer,
HeraldCondition $condition) {
$field = $this->requireFieldImplementation($condition->getFieldName());
return $field->getEditorValue(
$viewer,
$condition->getFieldCondition(),
$condition->getValue());
}
public function getEditorValueForAction(
PhabricatorUser $viewer,
HeraldActionRecord $action_record) {
$action = $this->requireActionImplementation($action_record->getAction());
return $action->getEditorValue(
$viewer,
$action_record->getTarget());
}
public function renderRuleAsText(
HeraldRule $rule,
PhabricatorHandleList $handles,
PhabricatorUser $viewer) {
require_celerity_resource('herald-css');
$icon = id(new PHUIIconView())
->setIcon('fa-chevron-circle-right lightgreytext')
->addClass('herald-list-icon');
if ($rule->getMustMatchAll()) {
$match_text = pht('When all of these conditions are met:');
} else {
$match_text = pht('When any of these conditions are met:');
}
$match_title = phutil_tag(
'p',
array(
'class' => 'herald-list-description',
),
$match_text);
$match_list = array();
foreach ($rule->getConditions() as $condition) {
$match_list[] = phutil_tag(
'div',
array(
'class' => 'herald-list-item',
),
array(
$icon,
$this->renderConditionAsText($condition, $handles, $viewer),
));
}
if ($rule->isRepeatFirst()) {
$action_text = pht(
'Take these actions the first time this rule matches:');
} else if ($rule->isRepeatOnChange()) {
$action_text = pht(
'Take these actions if this rule did not match the last time:');
} else {
$action_text = pht(
'Take these actions every time this rule matches:');
}
$action_title = phutil_tag(
'p',
array(
'class' => 'herald-list-description',
),
$action_text);
$action_list = array();
foreach ($rule->getActions() as $action) {
$action_list[] = phutil_tag(
'div',
array(
'class' => 'herald-list-item',
),
array(
$icon,
$this->renderActionAsText($viewer, $action, $handles),
));
}
return array(
$match_title,
$match_list,
$action_title,
$action_list,
);
}
private function renderConditionAsText(
HeraldCondition $condition,
PhabricatorHandleList $handles,
PhabricatorUser $viewer) {
$field_type = $condition->getFieldName();
$field = $this->getFieldImplementation($field_type);
if (!$field) {
return pht('Unknown Field: "%s"', $field_type);
}
$field_name = $field->getHeraldFieldName();
$condition_type = $condition->getFieldCondition();
$condition_name = idx($this->getConditionNameMap(), $condition_type);
$value = $this->renderConditionValueAsText($condition, $handles, $viewer);
return array(
$field_name,
' ',
$condition_name,
' ',
$value,
);
}
private function renderActionAsText(
PhabricatorUser $viewer,
HeraldActionRecord $action,
PhabricatorHandleList $handles) {
$impl = $this->getActionImplementation($action->getAction());
if ($impl) {
$impl->setViewer($viewer);
$value = $action->getTarget();
return $impl->renderActionDescription($value);
}
$rule_global = HeraldRuleTypeConfig::RULE_TYPE_GLOBAL;
$action_type = $action->getAction();
$default = pht('(Unknown Action "%s") equals', $action_type);
$action_name = idx(
$this->getActionNameMap($rule_global),
$action_type,
$default);
$target = $this->renderActionTargetAsText($action, $handles);
return hsprintf(' %s %s', $action_name, $target);
}
private function renderConditionValueAsText(
HeraldCondition $condition,
PhabricatorHandleList $handles,
PhabricatorUser $viewer) {
$field = $this->requireFieldImplementation($condition->getFieldName());
return $field->renderConditionValue(
$viewer,
$condition->getFieldCondition(),
$condition->getValue());
}
private function renderActionTargetAsText(
HeraldActionRecord $action,
PhabricatorHandleList $handles) {
// TODO: This should be driven through HeraldAction.
$target = $action->getTarget();
if (!is_array($target)) {
$target = array($target);
}
foreach ($target as $index => $val) {
switch ($action->getAction()) {
default:
$handle = $handles->getHandleIfExists($val);
if ($handle) {
$target[$index] = $handle->renderLink();
}
break;
}
}
$target = phutil_implode_html(', ', $target);
return $target;
}
/**
* Given a @{class:HeraldRule}, this function extracts all the phids that
* we'll want to load as handles later.
*
* This function performs a somewhat hacky approach to figuring out what
* is and is not a phid - try to get the phid type and if the type is
* *not* unknown assume its a valid phid.
*
* Don't try this at home. Use more strongly typed data at home.
*
* Think of the children.
*/
public static function getHandlePHIDs(HeraldRule $rule) {
$phids = array($rule->getAuthorPHID());
foreach ($rule->getConditions() as $condition) {
$value = $condition->getValue();
if (!is_array($value)) {
$value = array($value);
}
foreach ($value as $val) {
if (phid_get_type($val) !=
PhabricatorPHIDConstants::PHID_TYPE_UNKNOWN) {
$phids[] = $val;
}
}
}
foreach ($rule->getActions() as $action) {
$target = $action->getTarget();
if (!is_array($target)) {
$target = array($target);
}
foreach ($target as $val) {
if (phid_get_type($val) !=
PhabricatorPHIDConstants::PHID_TYPE_UNKNOWN) {
$phids[] = $val;
}
}
}
if ($rule->isObjectRule()) {
$phids[] = $rule->getTriggerObjectPHID();
}
return $phids;
}
/* -( Applying Effects )--------------------------------------------------- */
/**
* @task apply
*/
protected function applyStandardEffect(HeraldEffect $effect) {
$action = $effect->getAction();
$rule_type = $effect->getRule()->getRuleType();
$impl = $this->getActionImplementation($action);
if (!$impl) {
return new HeraldApplyTranscript(
$effect,
false,
array(
array(
HeraldAction::DO_STANDARD_INVALID_ACTION,
$action,
),
));
}
if (!$impl->supportsRuleType($rule_type)) {
return new HeraldApplyTranscript(
$effect,
false,
array(
array(
HeraldAction::DO_STANDARD_WRONG_RULE_TYPE,
$rule_type,
),
));
}
$impl->applyEffect($this->getObject(), $effect);
return $impl->getApplyTranscript($effect);
}
public function loadEdgePHIDs($type) {
if (!isset($this->edgeCache[$type])) {
$phids = PhabricatorEdgeQuery::loadDestinationPHIDs(
$this->getObject()->getPHID(),
$type);
$this->edgeCache[$type] = array_fuse($phids);
}
return $this->edgeCache[$type];
}
/* -( Forbidden Actions )-------------------------------------------------- */
final public function getForbiddenActions() {
return array_keys($this->forbiddenActions);
}
final public function setForbiddenAction($action, $reason) {
$this->forbiddenActions[$action] = $reason;
return $this;
}
final public function getRequiredFieldStates($field_key) {
return $this->requireFieldImplementation($field_key)
->getRequiredAdapterStates();
}
final public function getRequiredActionStates($action_key) {
return $this->requireActionImplementation($action_key)
->getRequiredAdapterStates();
}
final public function getForbiddenReason($action) {
if (!isset($this->forbiddenActions[$action])) {
throw new Exception(
pht(
'Action "%s" is not forbidden!',
$action));
}
return $this->forbiddenActions[$action];
}
/* -( Must Encrypt )------------------------------------------------------- */
final public function addMustEncryptReason($reason) {
$this->mustEncryptReasons[] = $reason;
return $this;
}
final public function getMustEncryptReasons() {
return $this->mustEncryptReasons;
}
/* -( Webhooks )----------------------------------------------------------- */
public function supportsWebhooks() {
return true;
}
final public function queueWebhook($webhook_phid, $rule_phid) {
$this->webhookMap[$webhook_phid][] = $rule_phid;
return $this;
}
final public function getWebhookMap() {
return $this->webhookMap;
}
}
diff --git a/src/applications/herald/controller/HeraldTranscriptController.php b/src/applications/herald/controller/HeraldTranscriptController.php
index 60dd6dc6ed..09a23408d3 100644
--- a/src/applications/herald/controller/HeraldTranscriptController.php
+++ b/src/applications/herald/controller/HeraldTranscriptController.php
@@ -1,600 +1,695 @@
<?php
final class HeraldTranscriptController extends HeraldController {
private $handles;
private $adapter;
private function getAdapter() {
return $this->adapter;
}
public function handleRequest(AphrontRequest $request) {
$viewer = $this->getViewer();
$xscript = id(new HeraldTranscriptQuery())
->setViewer($viewer)
->withIDs(array($request->getURIData('id')))
->executeOne();
if (!$xscript) {
return new Aphront404Response();
}
$object = $xscript->getObject();
require_celerity_resource('herald-test-css');
$content = array();
$object_xscript = $xscript->getObjectTranscript();
if (!$object_xscript) {
$notice = id(new PHUIInfoView())
->setSeverity(PHUIInfoView::SEVERITY_NOTICE)
->setTitle(pht('Old Transcript'))
->appendChild(phutil_tag(
'p',
array(),
pht('Details of this transcript have been garbage collected.')));
$content[] = $notice;
} else {
$map = HeraldAdapter::getEnabledAdapterMap($viewer);
$object_type = $object_xscript->getType();
if (empty($map[$object_type])) {
// TODO: We should filter these out in the Query, but we have to load
// the objectTranscript right now, which is potentially enormous. We
// should denormalize the object type, or move the data into a separate
// table, and then filter this earlier (and thus raise a better error).
// For now, just block access so we don't violate policies.
throw new Exception(
pht('This transcript has an invalid or inaccessible adapter.'));
}
$this->adapter = HeraldAdapter::getAdapterForContentType($object_type);
$phids = $this->getTranscriptPHIDs($xscript);
$phids = array_unique($phids);
$phids = array_filter($phids);
$handles = $this->loadViewerHandles($phids);
$this->handles = $handles;
if ($xscript->getDryRun()) {
$notice = new PHUIInfoView();
$notice->setSeverity(PHUIInfoView::SEVERITY_NOTICE);
$notice->setTitle(pht('Dry Run'));
$notice->appendChild(
pht(
'This was a dry run to test Herald rules, '.
'no actions were executed.'));
$content[] = $notice;
}
$warning_panel = $this->buildWarningPanel($xscript);
$content[] = $warning_panel;
$content[] = array(
$this->buildActionTranscriptPanel($xscript),
$this->buildObjectTranscriptPanel($xscript),
$this->buildTransactionsTranscriptPanel(
$object,
$xscript),
+ $this->buildProfilerTranscriptPanel($xscript),
);
}
$crumbs = id($this->buildApplicationCrumbs())
->addTextCrumb(
pht('Transcripts'),
$this->getApplicationURI('/transcript/'))
->addTextCrumb($xscript->getID())
->setBorder(true);
$title = pht('Transcript: %s', $xscript->getID());
$header = id(new PHUIHeaderView())
->setHeader($title)
->setHeaderIcon('fa-file');
$view = id(new PHUITwoColumnView())
->setHeader($header)
->setFooter($content);
return $this->newPage()
->setTitle($title)
->setCrumbs($crumbs)
->appendChild(
array(
$view,
));
}
protected function renderConditionTestValue($condition, $handles) {
// TODO: This is all a hacky mess and should be driven through FieldValue
// eventually.
switch ($condition->getFieldName()) {
case HeraldAnotherRuleField::FIELDCONST:
$value = array($condition->getTestValue());
break;
default:
$value = $condition->getTestValue();
break;
}
if (!is_scalar($value) && $value !== null) {
foreach ($value as $key => $phid) {
$handle = idx($handles, $phid);
if ($handle && $handle->isComplete()) {
$value[$key] = $handle->getName();
} else {
// This happens for things like task priorities, statuses, and
// custom fields.
$value[$key] = $phid;
}
}
sort($value);
$value = implode(', ', $value);
}
return phutil_tag('span', array('class' => 'condition-test-value'), $value);
}
protected function getTranscriptPHIDs($xscript) {
$phids = array();
$object_xscript = $xscript->getObjectTranscript();
if (!$object_xscript) {
return array();
}
$phids[] = $object_xscript->getPHID();
foreach ($xscript->getApplyTranscripts() as $apply_xscript) {
// TODO: This is total hacks. Add another amazing layer of abstraction.
$target = (array)$apply_xscript->getTarget();
foreach ($target as $phid) {
if ($phid) {
$phids[] = $phid;
}
}
}
foreach ($xscript->getRuleTranscripts() as $rule_xscript) {
$phids[] = $rule_xscript->getRuleOwner();
}
$condition_xscripts = $xscript->getConditionTranscripts();
if ($condition_xscripts) {
$condition_xscripts = call_user_func_array(
'array_merge',
$condition_xscripts);
}
foreach ($condition_xscripts as $condition_xscript) {
switch ($condition_xscript->getFieldName()) {
case HeraldAnotherRuleField::FIELDCONST:
$phids[] = $condition_xscript->getTestValue();
break;
default:
$value = $condition_xscript->getTestValue();
// TODO: Also total hacks.
if (is_array($value)) {
foreach ($value as $phid) {
if ($phid) {
// TODO: Probably need to make sure this
// "looks like" a PHID or decrease the level of hacks here;
// this used to be an is_numeric() check in Facebook land.
$phids[] = $phid;
}
}
}
break;
}
}
return $phids;
}
private function buildWarningPanel(HeraldTranscript $xscript) {
$request = $this->getRequest();
$panel = null;
if ($xscript->getObjectTranscript()) {
$handles = $this->handles;
$object_xscript = $xscript->getObjectTranscript();
$handle = $handles[$object_xscript->getPHID()];
if ($handle->getType() ==
PhabricatorRepositoryCommitPHIDType::TYPECONST) {
$commit = id(new DiffusionCommitQuery())
->setViewer($request->getUser())
->withPHIDs(array($handle->getPHID()))
->executeOne();
if ($commit) {
$repository = $commit->getRepository();
if ($repository->isImporting()) {
$title = pht(
'The %s repository is still importing.',
$repository->getMonogram());
$body = pht(
'Herald rules will not trigger until import completes.');
} else if (!$repository->isTracked()) {
$title = pht(
'The %s repository is not tracked.',
$repository->getMonogram());
$body = pht(
'Herald rules will not trigger until tracking is enabled.');
} else {
return $panel;
}
$panel = id(new PHUIInfoView())
->setSeverity(PHUIInfoView::SEVERITY_WARNING)
->setTitle($title)
->appendChild($body);
}
}
}
return $panel;
}
private function buildActionTranscriptPanel(HeraldTranscript $xscript) {
$action_xscript = mgroup($xscript->getApplyTranscripts(), 'getRuleID');
$adapter = $this->getAdapter();
$field_names = $adapter->getFieldNameMap();
$condition_names = $adapter->getConditionNameMap();
$handles = $this->handles;
$action_map = $xscript->getApplyTranscripts();
$action_map = mgroup($action_map, 'getRuleID');
$rule_list = id(new PHUIObjectItemListView())
->setNoDataString(pht('No Herald rules applied to this object.'))
->setFlush(true);
$rule_xscripts = $xscript->getRuleTranscripts();
$rule_xscripts = msort($rule_xscripts, 'getRuleID');
foreach ($rule_xscripts as $rule_xscript) {
$rule_id = $rule_xscript->getRuleID();
$rule_monogram = pht('H%d', $rule_id);
$rule_uri = '/'.$rule_monogram;
$rule_item = id(new PHUIObjectItemView())
->setObjectName($rule_monogram)
->setHeader($rule_xscript->getRuleName())
->setHref($rule_uri);
if (!$rule_xscript->getResult()) {
$rule_item->setDisabled(true);
}
$rule_list->addItem($rule_item);
// Build the field/condition transcript.
$cond_xscripts = $xscript->getConditionTranscriptsForRule($rule_id);
$cond_list = id(new PHUIStatusListView());
$cond_list->addItem(
id(new PHUIStatusItemView())
->setTarget(phutil_tag('strong', array(), pht('Conditions'))));
foreach ($cond_xscripts as $cond_xscript) {
if ($cond_xscript->isForbidden()) {
$icon = 'fa-ban';
$color = 'indigo';
$result = pht('Forbidden');
} else if ($cond_xscript->getResult()) {
$icon = 'fa-check';
$color = 'green';
$result = pht('Passed');
} else {
$icon = 'fa-times';
$color = 'red';
$result = pht('Failed');
}
if ($cond_xscript->getNote()) {
$note_text = $cond_xscript->getNote();
if ($cond_xscript->isForbidden()) {
$note_text = HeraldStateReasons::getExplanation($note_text);
}
$note = phutil_tag(
'div',
array(
'class' => 'herald-condition-note',
),
$note_text);
} else {
$note = null;
}
// TODO: This is not really translatable and should be driven through
// HeraldField.
$explanation = pht(
'%s %s %s',
idx($field_names, $cond_xscript->getFieldName(), pht('Unknown')),
idx($condition_names, $cond_xscript->getCondition(), pht('Unknown')),
$this->renderConditionTestValue($cond_xscript, $handles));
$cond_item = id(new PHUIStatusItemView())
->setIcon($icon, $color)
->setTarget($result)
->setNote(array($explanation, $note));
$cond_list->addItem($cond_item);
}
if ($rule_xscript->isForbidden()) {
$last_icon = 'fa-ban';
$last_color = 'indigo';
$last_result = pht('Forbidden');
$last_note = pht('Object state prevented rule evaluation.');
} else if ($rule_xscript->getResult()) {
$last_icon = 'fa-check-circle';
$last_color = 'green';
$last_result = pht('Passed');
$last_note = pht('Rule passed.');
} else {
$last_icon = 'fa-times-circle';
$last_color = 'red';
$last_result = pht('Failed');
$last_note = pht('Rule failed.');
}
$cond_last = id(new PHUIStatusItemView())
->setIcon($last_icon, $last_color)
->setTarget(phutil_tag('strong', array(), $last_result))
->setNote($last_note);
$cond_list->addItem($cond_last);
$cond_box = id(new PHUIBoxView())
->appendChild($cond_list)
->addMargin(PHUI::MARGIN_LARGE_LEFT);
$rule_item->appendChild($cond_box);
if (!$rule_xscript->getResult()) {
// If the rule didn't pass, don't generate an action transcript since
// actions didn't apply.
continue;
}
$cond_box->addMargin(PHUI::MARGIN_MEDIUM_BOTTOM);
$action_xscripts = idx($action_map, $rule_id, array());
foreach ($action_xscripts as $action_xscript) {
$action_key = $action_xscript->getAction();
$action = $adapter->getActionImplementation($action_key);
if ($action) {
$name = $action->getHeraldActionName();
$action->setViewer($this->getViewer());
} else {
$name = pht('Unknown Action ("%s")', $action_key);
}
$name = pht('Action: %s', $name);
$action_list = id(new PHUIStatusListView());
$action_list->addItem(
id(new PHUIStatusItemView())
->setTarget(phutil_tag('strong', array(), $name)));
$action_box = id(new PHUIBoxView())
->appendChild($action_list)
->addMargin(PHUI::MARGIN_LARGE_LEFT);
$rule_item->appendChild($action_box);
$log = $action_xscript->getAppliedReason();
// Handle older transcripts which used a static string to record
// action results.
if ($xscript->getDryRun()) {
$action_list->addItem(
id(new PHUIStatusItemView())
->setIcon('fa-ban', 'grey')
->setTarget(pht('Dry Run'))
->setNote(
pht(
'This was a dry run, so no actions were taken.')));
continue;
} else if (!is_array($log)) {
$action_list->addItem(
id(new PHUIStatusItemView())
->setIcon('fa-clock-o', 'grey')
->setTarget(pht('Old Transcript'))
->setNote(
pht(
'This is an old transcript which uses an obsolete log '.
'format. Detailed action information is not available.')));
continue;
}
foreach ($log as $entry) {
$type = idx($entry, 'type');
$data = idx($entry, 'data');
if ($action) {
$icon = $action->renderActionEffectIcon($type, $data);
$color = $action->renderActionEffectColor($type, $data);
$name = $action->renderActionEffectName($type, $data);
$note = $action->renderEffectDescription($type, $data);
} else {
$icon = 'fa-question-circle';
$color = 'indigo';
$name = pht('Unknown Effect ("%s")', $type);
$note = null;
}
$action_item = id(new PHUIStatusItemView())
->setIcon($icon, $color)
->setTarget($name)
->setNote($note);
$action_list->addItem($action_item);
}
}
}
$box = id(new PHUIObjectBoxView())
->setHeaderText(pht('Rule Transcript'))
->appendChild($rule_list);
return $box;
}
private function buildObjectTranscriptPanel(HeraldTranscript $xscript) {
$adapter = $this->getAdapter();
$field_names = $adapter->getFieldNameMap();
$object_xscript = $xscript->getObjectTranscript();
$data = array();
if ($object_xscript) {
$phid = $object_xscript->getPHID();
$handles = $this->handles;
$data += array(
pht('Object Name') => $object_xscript->getName(),
pht('Object Type') => $object_xscript->getType(),
pht('Object PHID') => $phid,
pht('Object Link') => $handles[$phid]->renderLink(),
);
}
$data += $xscript->getMetadataMap();
if ($object_xscript) {
foreach ($object_xscript->getFields() as $field => $value) {
$field = idx($field_names, $field, '['.$field.'?]');
$data['Field: '.$field] = $value;
}
}
$rows = array();
foreach ($data as $name => $value) {
if (!($value instanceof PhutilSafeHTML)) {
if (!is_scalar($value) && !is_null($value)) {
$value = implode("\n", $value);
}
if (strlen($value) > 256) {
$value = phutil_tag(
'textarea',
array(
'class' => 'herald-field-value-transcript',
),
$value);
}
}
$rows[] = array($name, $value);
}
$property_list = new PHUIPropertyListView();
$property_list->setStacked(true);
foreach ($rows as $row) {
$property_list->addProperty($row[0], $row[1]);
}
$box = new PHUIObjectBoxView();
$box->setHeaderText(pht('Object Transcript'));
$box->appendChild($property_list);
return $box;
}
private function buildTransactionsTranscriptPanel(
$object,
HeraldTranscript $xscript) {
$viewer = $this->getViewer();
$object_xscript = $xscript->getObjectTranscript();
$xaction_phids = $object_xscript->getAppliedTransactionPHIDs();
// If the value is "null", this is an older transcript or this adapter
// does not use transactions. We render nothing.
//
// If the value is "array()", this is a modern transcript which uses
// transactions, there just weren't any applied. Below, we'll render a
// "No Transactions Applied" state.
if ($xaction_phids === null) {
return null;
}
// If this object doesn't implement the right interface, we won't be
// able to load the transactions. Just bail.
if (!($object instanceof PhabricatorApplicationTransactionInterface)) {
return null;
}
$query = PhabricatorApplicationTransactionQuery::newQueryForObject(
$object);
if ($xaction_phids) {
$xactions = $query
->setViewer($viewer)
->withPHIDs($xaction_phids)
->execute();
$xactions = mpull($xactions, null, 'getPHID');
} else {
$xactions = array();
}
$rows = array();
foreach ($xaction_phids as $xaction_phid) {
$xaction = idx($xactions, $xaction_phid);
$xaction_identifier = $xaction_phid;
$xaction_date = null;
$xaction_display = null;
if ($xaction) {
$xaction_identifier = $xaction->getID();
$xaction_date = phabricator_datetime(
$xaction->getDateCreated(),
$viewer);
// Since we don't usually render transactions outside of the context
// of objects, some of them might depend on missing object data. Out of
// an abundance of caution, catch any rendering issues.
try {
$xaction_display = $xaction->getTitle();
} catch (Exception $ex) {
$xaction_display = $ex->getMessage();
}
}
$rows[] = array(
$xaction_identifier,
$xaction_display,
$xaction_date,
);
}
$table_view = id(new AphrontTableView($rows))
->setHeaders(
array(
pht('ID'),
pht('Transaction'),
pht('Date'),
))
->setColumnClasses(
array(
null,
'wide',
null,
));
$box_view = id(new PHUIObjectBoxView())
->setHeaderText(pht('Transactions'))
->setTable($table_view);
return $box_view;
}
+ private function buildProfilerTranscriptPanel(HeraldTranscript $xscript) {
+ $viewer = $this->getViewer();
+
+ $object_xscript = $xscript->getObjectTranscript();
+
+ $profile = $object_xscript->getProfile();
+
+ // If this is an older transcript without profiler information, don't
+ // show anything.
+ if ($profile === null) {
+ return null;
+ }
+
+ $profile = isort($profile, 'elapsed');
+ $profile = array_reverse($profile);
+
+ $phids = array();
+ foreach ($profile as $frame) {
+ if ($frame['type'] === 'rule') {
+ $phids[] = $frame['key'];
+ }
+ }
+ $handles = $viewer->loadHandles($phids);
+
+ $field_map = HeraldField::getAllFields();
+
+ $rows = array();
+ foreach ($profile as $frame) {
+ $cost = $frame['elapsed'];
+ $cost = 1000000 * $cost;
+ $cost = pht('%sus', new PhutilNumber($cost));
+
+ $type = $frame['type'];
+ switch ($type) {
+ case 'rule':
+ $type_display = pht('Rule');
+ break;
+ case 'field':
+ $type_display = pht('Field');
+ break;
+ default:
+ $type_display = $type;
+ break;
+ }
+
+ $key = $frame['key'];
+ switch ($type) {
+ case 'field':
+ $field_object = idx($field_map, $key);
+ if ($field_object) {
+ $key_display = $field_object->getHeraldFieldName();
+ } else {
+ $key_display = $key;
+ }
+ break;
+ case 'rule':
+ $key_display = $handles[$key]->renderLink();
+ break;
+ default:
+ $key_display = $key;
+ break;
+ }
+
+ $rows[] = array(
+ $type_display,
+ $key_display,
+ $cost,
+ pht('%s', new PhutilNumber($frame['count'])),
+ );
+ }
+
+ $table_view = id(new AphrontTableView($rows))
+ ->setHeaders(
+ array(
+ pht('Type'),
+ pht('What'),
+ pht('Cost'),
+ pht('Count'),
+ ))
+ ->setColumnClasses(
+ array(
+ null,
+ 'wide',
+ 'right',
+ 'right',
+ ));
+
+ $box_view = id(new PHUIObjectBoxView())
+ ->setHeaderText(pht('Profile'))
+ ->setTable($table_view);
+
+ return $box_view;
+ }
+
}
diff --git a/src/applications/herald/engine/HeraldEngine.php b/src/applications/herald/engine/HeraldEngine.php
index 2d96532882..9ca72821e7 100644
--- a/src/applications/herald/engine/HeraldEngine.php
+++ b/src/applications/herald/engine/HeraldEngine.php
@@ -1,640 +1,785 @@
<?php
final class HeraldEngine extends Phobject {
protected $rules = array();
protected $results = array();
protected $stack = array();
protected $activeRule;
protected $transcript;
protected $fieldCache = array();
protected $object;
private $dryRun;
private $forbiddenFields = array();
private $forbiddenActions = array();
private $skipEffects = array();
+ private $profilerStack = array();
+ private $profilerFrames = array();
+
public function setDryRun($dry_run) {
$this->dryRun = $dry_run;
return $this;
}
public function getDryRun() {
return $this->dryRun;
}
public function getRule($phid) {
return idx($this->rules, $phid);
}
public function loadRulesForAdapter(HeraldAdapter $adapter) {
return id(new HeraldRuleQuery())
->setViewer(PhabricatorUser::getOmnipotentUser())
->withDisabled(false)
->withContentTypes(array($adapter->getAdapterContentType()))
->needConditionsAndActions(true)
->needAppliedToPHIDs(array($adapter->getPHID()))
->needValidateAuthors(true)
->execute();
}
public static function loadAndApplyRules(HeraldAdapter $adapter) {
$engine = new HeraldEngine();
$rules = $engine->loadRulesForAdapter($adapter);
$effects = $engine->applyRules($rules, $adapter);
$engine->applyEffects($effects, $adapter, $rules);
return $engine->getTranscript();
}
public function applyRules(array $rules, HeraldAdapter $object) {
assert_instances_of($rules, 'HeraldRule');
$t_start = microtime(true);
// Rules execute in a well-defined order: sort them into execution order.
$rules = msort($rules, 'getRuleExecutionOrderSortKey');
$rules = mpull($rules, null, 'getPHID');
$this->transcript = new HeraldTranscript();
$this->transcript->setObjectPHID((string)$object->getPHID());
$this->fieldCache = array();
$this->results = array();
$this->rules = $rules;
$this->object = $object;
$effects = array();
foreach ($rules as $phid => $rule) {
$this->stack = array();
$is_first_only = $rule->isRepeatFirst();
try {
if (!$this->getDryRun() &&
$is_first_only &&
$rule->getRuleApplied($object->getPHID())) {
// This is not a dry run, and this rule is only supposed to be
// applied a single time, and it's already been applied...
// That means automatic failure.
$this->newRuleTranscript($rule)
->setResult(false)
->setReason(
pht(
'This rule is only supposed to be repeated a single time, '.
'and it has already been applied.'));
$rule_matches = false;
} else {
if ($this->isForbidden($rule, $object)) {
$this->newRuleTranscript($rule)
->setResult(HeraldRuleTranscript::RESULT_FORBIDDEN)
->setReason(
pht(
'Object state is not compatible with rule.'));
$rule_matches = false;
} else {
$rule_matches = $this->doesRuleMatch($rule, $object);
}
}
} catch (HeraldRecursiveConditionsException $ex) {
$names = array();
foreach ($this->stack as $rule_phid => $ignored) {
$names[] = '"'.$rules[$rule_phid]->getName().'"';
}
$names = implode(', ', $names);
foreach ($this->stack as $rule_phid => $ignored) {
$this->newRuleTranscript($rules[$rule_phid])
->setResult(false)
->setReason(
pht(
"Rules %s are recursively dependent upon one another! ".
"Don't do this! You have formed an unresolvable cycle in the ".
"dependency graph!",
$names));
}
$rule_matches = false;
}
$this->results[$phid] = $rule_matches;
if ($rule_matches) {
foreach ($this->getRuleEffects($rule, $object) as $effect) {
$effects[] = $effect;
}
}
}
$xaction_phids = null;
$xactions = $object->getAppliedTransactions();
if ($xactions !== null) {
$xaction_phids = mpull($xactions, 'getPHID');
}
$object_transcript = id(new HeraldObjectTranscript())
->setPHID($object->getPHID())
->setName($object->getHeraldName())
->setType($object->getAdapterContentType())
->setFields($this->fieldCache)
- ->setAppliedTransactionPHIDs($xaction_phids);
+ ->setAppliedTransactionPHIDs($xaction_phids)
+ ->setProfile($this->getProfile());
$this->transcript->setObjectTranscript($object_transcript);
$t_end = microtime(true);
$this->transcript->setDuration($t_end - $t_start);
return $effects;
}
public function applyEffects(
array $effects,
HeraldAdapter $adapter,
array $rules) {
assert_instances_of($effects, 'HeraldEffect');
assert_instances_of($rules, 'HeraldRule');
$this->transcript->setDryRun((int)$this->getDryRun());
if ($this->getDryRun()) {
$xscripts = array();
foreach ($effects as $effect) {
$xscripts[] = new HeraldApplyTranscript(
$effect,
false,
pht('This was a dry run, so no actions were actually taken.'));
}
} else {
$xscripts = $adapter->applyHeraldEffects($effects);
}
assert_instances_of($xscripts, 'HeraldApplyTranscript');
foreach ($xscripts as $apply_xscript) {
$this->transcript->addApplyTranscript($apply_xscript);
}
// For dry runs, don't mark the rule as having applied to the object.
if ($this->getDryRun()) {
return;
}
// Update the "applied" state table. How this table works depends on the
// repetition policy for the rule.
//
// REPEAT_EVERY: We delete existing rows for the rule, then write nothing.
// This policy doesn't use any state.
//
// REPEAT_FIRST: We keep existing rows, then write additional rows for
// rules which fired. This policy accumulates state over the life of the
// object.
//
// REPEAT_CHANGE: We delete existing rows, then write all the rows which
// matched. This policy only uses the state from the previous run.
$rules = mpull($rules, null, 'getID');
$rule_ids = mpull($xscripts, 'getRuleID');
$delete_ids = array();
foreach ($rules as $rule_id => $rule) {
if ($rule->isRepeatFirst()) {
continue;
}
$delete_ids[] = $rule_id;
}
$applied_ids = array();
foreach ($rule_ids as $rule_id) {
if (!$rule_id) {
// Some apply transcripts are purely informational and not associated
// with a rule, e.g. carryover emails from earlier revisions.
continue;
}
$rule = idx($rules, $rule_id);
if (!$rule) {
continue;
}
if ($rule->isRepeatFirst() || $rule->isRepeatOnChange()) {
$applied_ids[] = $rule_id;
}
}
// Also include "only if this rule did not match the last time" rules
// which matched but were skipped in the "applied" list.
foreach ($this->skipEffects as $rule_id => $ignored) {
$applied_ids[] = $rule_id;
}
if ($delete_ids || $applied_ids) {
$conn_w = id(new HeraldRule())->establishConnection('w');
if ($delete_ids) {
queryfx(
$conn_w,
'DELETE FROM %T WHERE phid = %s AND ruleID IN (%Ld)',
HeraldRule::TABLE_RULE_APPLIED,
$adapter->getPHID(),
$delete_ids);
}
if ($applied_ids) {
$sql = array();
foreach ($applied_ids as $id) {
$sql[] = qsprintf(
$conn_w,
'(%s, %d)',
$adapter->getPHID(),
$id);
}
queryfx(
$conn_w,
'INSERT IGNORE INTO %T (phid, ruleID) VALUES %LQ',
HeraldRule::TABLE_RULE_APPLIED,
$sql);
}
}
}
public function getTranscript() {
$this->transcript->save();
return $this->transcript;
}
public function doesRuleMatch(
HeraldRule $rule,
HeraldAdapter $object) {
$phid = $rule->getPHID();
if (isset($this->results[$phid])) {
// If we've already evaluated this rule because another rule depends
// on it, we don't need to reevaluate it.
return $this->results[$phid];
}
if (isset($this->stack[$phid])) {
// We've recursed, fail all of the rules on the stack. This happens when
// there's a dependency cycle with "Rule conditions match for rule ..."
// conditions.
foreach ($this->stack as $rule_phid => $ignored) {
$this->results[$rule_phid] = false;
}
throw new HeraldRecursiveConditionsException();
}
$this->stack[$phid] = true;
$all = $rule->getMustMatchAll();
$conditions = $rule->getConditions();
$result = null;
$local_version = id(new HeraldRule())->getConfigVersion();
if ($rule->getConfigVersion() > $local_version) {
$reason = pht(
'Rule could not be processed, it was created with a newer version '.
'of Herald.');
$result = false;
} else if (!$conditions) {
$reason = pht(
'Rule failed automatically because it has no conditions.');
$result = false;
} else if (!$rule->hasValidAuthor()) {
$reason = pht(
'Rule failed automatically because its owner is invalid '.
'or disabled.');
$result = false;
} else if (!$this->canAuthorViewObject($rule, $object)) {
$reason = pht(
'Rule failed automatically because it is a personal rule and its '.
'owner can not see the object.');
$result = false;
} else if (!$this->canRuleApplyToObject($rule, $object)) {
$reason = pht(
'Rule failed automatically because it is an object rule which is '.
'not relevant for this object.');
$result = false;
} else {
foreach ($conditions as $condition) {
try {
$this->getConditionObjectValue($condition, $object);
} catch (Exception $ex) {
$reason = pht(
'Field "%s" does not exist!',
$condition->getFieldName());
$result = false;
break;
}
- $match = $this->doesConditionMatch($rule, $condition, $object);
+ // Here, we're profiling the cost to match the condition value against
+ // whatever test is configured. Normally, this cost should be very
+ // small (<<1ms) since it amounts to a single comparison:
+ //
+ // [ Task author ][ is any of ][ alice ]
+ //
+ // However, it may be expensive in some cases, particularly if you
+ // write a rule with a very creative regular expression that backtracks
+ // explosively.
+ //
+ // At time of writing, the "Another Herald Rule" field is also
+ // evaluated inside the matching function. This may be arbitrarily
+ // expensive (it can prompt us to execute any finite number of other
+ // Herald rules), although we'll push the profiler stack appropriately
+ // so we don't count the evaluation time against this rule in the final
+ // profile.
+
+ $caught = null;
+
+ $this->pushProfilerRule($rule);
+ try {
+ $match = $this->doesConditionMatch($rule, $condition, $object);
+ } catch (Exception $ex) {
+ $caught = $ex;
+ }
+ $this->popProfilerRule($rule);
+
+ if ($caught) {
+ throw $ex;
+ }
if (!$all && $match) {
$reason = pht('Any condition matched.');
$result = true;
break;
}
if ($all && !$match) {
$reason = pht('Not all conditions matched.');
$result = false;
break;
}
}
if ($result === null) {
if ($all) {
$reason = pht('All conditions matched.');
$result = true;
} else {
$reason = pht('No conditions matched.');
$result = false;
}
}
}
// If this rule matched, and is set to run "if it did not match the last
// time", and we matched the last time, we're going to return a match in
// the transcript but set a flag so we don't actually apply any effects.
// We need the rule to match so that storage gets updated properly. If we
// just pretend the rule didn't match it won't cause any effects (which
// is correct), but it also won't set the "it matched" flag in storage,
// so the next run after this one would incorrectly trigger again.
$is_dry_run = $this->getDryRun();
if ($result && !$is_dry_run) {
$is_on_change = $rule->isRepeatOnChange();
if ($is_on_change) {
$did_apply = $rule->getRuleApplied($object->getPHID());
if ($did_apply) {
$reason = pht(
'This rule matched, but did not take any actions because it '.
'is configured to act only if it did not match the last time.');
$this->skipEffects[$rule->getID()] = true;
}
}
}
$this->newRuleTranscript($rule)
->setResult($result)
->setReason($reason);
return $result;
}
protected function doesConditionMatch(
HeraldRule $rule,
HeraldCondition $condition,
HeraldAdapter $object) {
$object_value = $this->getConditionObjectValue($condition, $object);
$transcript = $this->newConditionTranscript($rule, $condition);
try {
$result = $object->doesConditionMatch(
$this,
$rule,
$condition,
$object_value);
} catch (HeraldInvalidConditionException $ex) {
$result = false;
$transcript->setNote($ex->getMessage());
}
$transcript->setResult($result);
return $result;
}
protected function getConditionObjectValue(
HeraldCondition $condition,
HeraldAdapter $object) {
$field = $condition->getFieldName();
return $this->getObjectFieldValue($field);
}
public function getObjectFieldValue($field) {
if (!array_key_exists($field, $this->fieldCache)) {
- $this->fieldCache[$field] = $this->object->getHeraldField($field);
+ $adapter = $this->object;
+
+ $adapter->willGetHeraldField($field);
+
+ $caught = null;
+
+ $this->pushProfilerField($field);
+ try {
+ $value = $adapter->getHeraldField($field);
+ } catch (Exception $ex) {
+ $caught = $ex;
+ }
+ $this->popProfilerField($field);
+
+ if ($caught) {
+ throw $caught;
+ }
+
+ $this->fieldCache[$field] = $value;
}
return $this->fieldCache[$field];
}
protected function getRuleEffects(
HeraldRule $rule,
HeraldAdapter $object) {
$rule_id = $rule->getID();
if (isset($this->skipEffects[$rule_id])) {
return array();
}
$effects = array();
foreach ($rule->getActions() as $action) {
$effect = id(new HeraldEffect())
->setObjectPHID($object->getPHID())
->setAction($action->getAction())
->setTarget($action->getTarget())
->setRule($rule);
$name = $rule->getName();
$id = $rule->getID();
$effect->setReason(
pht(
'Conditions were met for %s',
"H{$id} {$name}"));
$effects[] = $effect;
}
return $effects;
}
private function canAuthorViewObject(
HeraldRule $rule,
HeraldAdapter $adapter) {
// Authorship is irrelevant for global rules and object rules.
if ($rule->isGlobalRule() || $rule->isObjectRule()) {
return true;
}
// The author must be able to create rules for the adapter's content type.
// In particular, this means that the application must be installed and
// accessible to the user. For example, if a user writes a Differential
// rule and then loses access to Differential, this disables the rule.
$enabled = HeraldAdapter::getEnabledAdapterMap($rule->getAuthor());
if (empty($enabled[$adapter->getAdapterContentType()])) {
return false;
}
// Finally, the author must be able to see the object itself. You can't
// write a personal rule that CC's you on revisions you wouldn't otherwise
// be able to see, for example.
$object = $adapter->getObject();
return PhabricatorPolicyFilter::hasCapability(
$rule->getAuthor(),
$object,
PhabricatorPolicyCapability::CAN_VIEW);
}
private function canRuleApplyToObject(
HeraldRule $rule,
HeraldAdapter $adapter) {
// Rules which are not object rules can apply to anything.
if (!$rule->isObjectRule()) {
return true;
}
$trigger_phid = $rule->getTriggerObjectPHID();
$object_phids = $adapter->getTriggerObjectPHIDs();
if ($object_phids) {
if (in_array($trigger_phid, $object_phids)) {
return true;
}
}
return false;
}
private function newRuleTranscript(HeraldRule $rule) {
$xscript = id(new HeraldRuleTranscript())
->setRuleID($rule->getID())
->setRuleName($rule->getName())
->setRuleOwner($rule->getAuthorPHID());
$this->transcript->addRuleTranscript($xscript);
return $xscript;
}
private function newConditionTranscript(
HeraldRule $rule,
HeraldCondition $condition) {
$xscript = id(new HeraldConditionTranscript())
->setRuleID($rule->getID())
->setConditionID($condition->getID())
->setFieldName($condition->getFieldName())
->setCondition($condition->getFieldCondition())
->setTestValue($condition->getValue());
$this->transcript->addConditionTranscript($xscript);
return $xscript;
}
private function newApplyTranscript(
HeraldAdapter $adapter,
HeraldRule $rule,
HeraldActionRecord $action) {
$effect = id(new HeraldEffect())
->setObjectPHID($adapter->getPHID())
->setAction($action->getAction())
->setTarget($action->getTarget())
->setRule($rule);
$xscript = new HeraldApplyTranscript($effect, false);
$this->transcript->addApplyTranscript($xscript);
return $xscript;
}
private function isForbidden(
HeraldRule $rule,
HeraldAdapter $adapter) {
$forbidden = $adapter->getForbiddenActions();
if (!$forbidden) {
return false;
}
$forbidden = array_fuse($forbidden);
$is_forbidden = false;
foreach ($rule->getConditions() as $condition) {
$field_key = $condition->getFieldName();
if (!isset($this->forbiddenFields[$field_key])) {
$reason = null;
try {
$states = $adapter->getRequiredFieldStates($field_key);
} catch (Exception $ex) {
$states = array();
}
foreach ($states as $state) {
if (!isset($forbidden[$state])) {
continue;
}
$reason = $adapter->getForbiddenReason($state);
break;
}
$this->forbiddenFields[$field_key] = $reason;
}
$forbidden_reason = $this->forbiddenFields[$field_key];
if ($forbidden_reason !== null) {
$this->newConditionTranscript($rule, $condition)
->setResult(HeraldConditionTranscript::RESULT_FORBIDDEN)
->setNote($forbidden_reason);
$is_forbidden = true;
}
}
foreach ($rule->getActions() as $action_record) {
$action_key = $action_record->getAction();
if (!isset($this->forbiddenActions[$action_key])) {
$reason = null;
try {
$states = $adapter->getRequiredActionStates($action_key);
} catch (Exception $ex) {
$states = array();
}
foreach ($states as $state) {
if (!isset($forbidden[$state])) {
continue;
}
$reason = $adapter->getForbiddenReason($state);
break;
}
$this->forbiddenActions[$action_key] = $reason;
}
$forbidden_reason = $this->forbiddenActions[$action_key];
if ($forbidden_reason !== null) {
$this->newApplyTranscript($adapter, $rule, $action_record)
->setAppliedReason(
array(
array(
'type' => HeraldAction::DO_STANDARD_FORBIDDEN,
'data' => $forbidden_reason,
),
));
$is_forbidden = true;
}
}
return $is_forbidden;
}
+/* -( Profiler )----------------------------------------------------------- */
+
+ private function pushProfilerField($field_key) {
+ return $this->pushProfilerStack('field', $field_key);
+ }
+
+ private function popProfilerField($field_key) {
+ return $this->popProfilerStack('field', $field_key);
+ }
+
+ private function pushProfilerRule(HeraldRule $rule) {
+ return $this->pushProfilerStack('rule', $rule->getPHID());
+ }
+
+ private function popProfilerRule(HeraldRule $rule) {
+ return $this->popProfilerStack('rule', $rule->getPHID());
+ }
+
+ private function pushProfilerStack($type, $key) {
+ $this->profilerStack[] = array(
+ 'type' => $type,
+ 'key' => $key,
+ 'start' => microtime(true),
+ );
+
+ return $this;
+ }
+
+ private function popProfilerStack($type, $key) {
+ if (!$this->profilerStack) {
+ throw new Exception(
+ pht(
+ 'Unable to pop profiler stack: profiler stack is empty.'));
+ }
+
+ $frame = last($this->profilerStack);
+ if (($frame['type'] !== $type) || ($frame['key'] !== $key)) {
+ throw new Exception(
+ pht(
+ 'Unable to pop profiler stack: expected frame of type "%s" with '.
+ 'key "%s", but found frame of type "%s" with key "%s".',
+ $type,
+ $key,
+ $frame['type'],
+ $frame['key']));
+ }
+
+ // Accumulate the new timing information into the existing profile. If this
+ // is the first time we've seen this particular rule or field, we'll
+ // create a new empty frame first.
+
+ $elapsed = microtime(true) - $frame['start'];
+ $frame_key = sprintf('%s/%s', $type, $key);
+
+ if (!isset($this->profilerFrames[$frame_key])) {
+ $current = array(
+ 'type' => $type,
+ 'key' => $key,
+ 'elapsed' => 0,
+ 'count' => 0,
+ );
+ } else {
+ $current = $this->profilerFrames[$frame_key];
+ }
+
+ $current['elapsed'] += $elapsed;
+ $current['count']++;
+
+ $this->profilerFrames[$frame_key] = $current;
+
+ array_pop($this->profilerStack);
+ }
+
+ private function getProfile() {
+ if ($this->profilerStack) {
+ $frame = last($this->profilerStack);
+ $frame_type = $frame['type'];
+ $frame_key = $frame['key'];
+ $frame_count = count($this->profilerStack);
+
+ throw new Exception(
+ pht(
+ 'Unable to retrieve profile: profiler stack is not empty. The '.
+ 'stack has %s frame(s); the final frame has type "%s" and key '.
+ '"%s".',
+ new PhutilNumber($frame_count),
+ $frame_type,
+ $frame_key));
+ }
+
+ return array_values($this->profilerFrames);
+ }
+
+
}
diff --git a/src/applications/herald/storage/transcript/HeraldObjectTranscript.php b/src/applications/herald/storage/transcript/HeraldObjectTranscript.php
index 9d331b271e..b5f9aa783f 100644
--- a/src/applications/herald/storage/transcript/HeraldObjectTranscript.php
+++ b/src/applications/herald/storage/transcript/HeraldObjectTranscript.php
@@ -1,85 +1,95 @@
<?php
final class HeraldObjectTranscript extends Phobject {
protected $phid;
protected $type;
protected $name;
protected $fields;
protected $appliedTransactionPHIDs;
+ protected $profile;
public function setPHID($phid) {
$this->phid = $phid;
return $this;
}
public function getPHID() {
return $this->phid;
}
public function setType($type) {
$this->type = $type;
return $this;
}
public function getType() {
return $this->type;
}
public function setName($name) {
$this->name = $name;
return $this;
}
public function getName() {
return $this->name;
}
public function setFields(array $fields) {
foreach ($fields as $key => $value) {
$fields[$key] = self::truncateValue($value, 4096);
}
$this->fields = $fields;
return $this;
}
public function getFields() {
return $this->fields;
}
+ public function setProfile(array $profile) {
+ $this->profile = $profile;
+ return $this;
+ }
+
+ public function getProfile() {
+ return $this->profile;
+ }
+
public function setAppliedTransactionPHIDs($phids) {
$this->appliedTransactionPHIDs = $phids;
return $this;
}
public function getAppliedTransactionPHIDs() {
return $this->appliedTransactionPHIDs;
}
private static function truncateValue($value, $length) {
if (is_string($value)) {
if (strlen($value) <= $length) {
return $value;
} else {
// NOTE: PhutilUTF8StringTruncator has huge runtime for giant strings.
return phutil_utf8ize(substr($value, 0, $length)."\n<...>");
}
} else if (is_array($value)) {
foreach ($value as $key => $v) {
if ($length <= 0) {
$value['<...>'] = '<...>';
unset($value[$key]);
} else {
$v = self::truncateValue($v, $length);
$length -= strlen($v);
$value[$key] = $v;
}
}
return $value;
} else {
return $value;
}
}
}

File Metadata

Mime Type
text/x-diff
Expires
Wed, Jul 2, 10:06 AM (1 d, 18 h)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
164842
Default Alt Text
(84 KB)

Event Timeline