use onetaskgraph_plugin_api::{NativeId, SourceError, Task, unwritable_field};
use serde_json::{Value, json};
use super::{KIND, LinearSource, graphql, shared, str_at};
const USERS_PAGE: usize = 250;
const USERS_CONNECTIONS: usize = 33;
pub const PEOPLE_PER_LOOKUP: usize = USERS_PAGE * USERS_CONNECTIONS;
pub(crate) fn read(v: &Value) -> Result<Vec<String>, SourceError> {
match v.get("assignee") {
None => Err(SourceError::Malformed {
message: "an issue of a source reading assignees was answered without its assignee"
.to_owned(),
}),
Some(Value::Null) => Ok(Vec::new()),
Some(user) => Ok(vec![str_at(user, "displayName")?.to_owned()]),
}
}
pub(crate) fn carried(variables: &Value) -> bool {
variables.as_object().is_some_and(|variables| {
variables
.iter()
.any(|(name, value)| name.starts_with("input") && value.get("assigneeId").is_some())
})
}
pub(crate) fn create_input(mut input: Value) -> Value {
if let Some(members) = input.as_object_mut()
&& members.get("assigneeId").is_some_and(Value::is_null)
{
members.remove("assigneeId");
}
input
}
pub(crate) fn asked(people: Option<&[String]>, create: bool) -> Option<&[String]> {
people.filter(|people| !(create && people.is_empty()))
}
pub(crate) fn named<'a>(people: impl IntoIterator<Item = &'a [String]>) -> Vec<&'a str> {
let mut named: Vec<&str> = Vec::new();
for person in people.into_iter().flatten() {
if !named.contains(&person.as_str()) {
named.push(person);
}
}
named
}
impl LinearSource {
pub(crate) fn assignees_writable(&self, people: Option<&[String]>) -> Result<(), SourceError> {
let Some(people) = people else {
return Ok(());
};
if !self.assignees {
return Err(unwritable_field(KIND, "assignees"));
}
if people.len() > 1 {
return Err(SourceError::Refused {
message: format!(
"a Linear issue holds one assignee, and the write to source {} names {}; \
next: name one person, or none",
self.name,
people.len()
),
});
}
Ok(())
}
pub(crate) async fn assignee_id(&self, wanted: &[String]) -> Result<Value, SourceError> {
self.assignees_writable(Some(wanted))?;
match wanted.first() {
None => Ok(Value::Null),
Some(person) => Ok(json!(self.person_id(person).await?)),
}
}
pub(crate) async fn resolve_people(&self, names: &[&str]) -> Result<(), SourceError> {
let tracker = self.tracker();
let unresolved: Vec<String> = {
let held = shared::people();
let unknown = self.unknown();
names
.iter()
.filter(|name| {
!held.contains_key(&(tracker.clone(), (**name).to_owned()))
&& !unknown.contains(**name)
})
.map(|name| (*name).to_owned())
.collect()
};
for request in unresolved.chunks(PEOPLE_PER_LOOKUP) {
let pages: Vec<&[String]> = request.chunks(USERS_PAGE).collect();
let answered: Vec<(Option<Value>, &[String])> = if let [asked] = pages.as_slice() {
let data = self
.send(
graphql::USERS,
json!({"names": asked, "first": asked.len()}),
)
.await?;
vec![(data.get("users").cloned(), *asked)]
} else {
let mut variables = serde_json::Map::new();
for (at, asked) in pages.iter().enumerate() {
variables.insert(format!("names_{at}"), json!(asked));
variables.insert(format!("first_{at}"), json!(asked.len()));
}
let data = self
.send(
&graphql::aliased(graphql::USERS, pages.len()),
Value::Object(variables),
)
.await?;
pages
.iter()
.enumerate()
.map(|(at, asked)| (data.get(format!("a{at}")).cloned(), *asked))
.collect()
};
for (users, asked) in answered {
self.hold_people(users.as_ref(), asked)?;
}
}
Ok(())
}
fn hold_people(&self, users: Option<&Value>, asked: &[String]) -> Result<(), SourceError> {
let tracker = self.tracker();
let nodes = users
.and_then(|users| users.get("nodes"))
.and_then(Value::as_array)
.ok_or_else(|| SourceError::Malformed {
message: "missing users.nodes".to_owned(),
})?;
let mut found: std::collections::BTreeMap<String, String> =
std::collections::BTreeMap::new();
for node in nodes {
let name = str_at(node, "displayName")?;
let id = str_at(node, "id")?;
if !asked.iter().any(|asked| asked == name) {
continue;
}
if found.insert(name.to_owned(), id.to_owned()).is_some() {
return Err(SourceError::Malformed {
message: format!(
"Linear answered two users displayed as {name:?}, a name its schema says \
is unique within the workspace"
),
});
}
}
let mut unknown = self.unknown();
let mut held = shared::people();
for name in asked {
match found.remove(name) {
Some(id) => {
held.insert((tracker.clone(), name.clone()), id);
}
None => {
unknown.insert(name.clone());
}
}
}
Ok(())
}
pub(crate) async fn person_id(&self, name: &str) -> Result<String, SourceError> {
self.resolve_people(&[name]).await?;
if let Some(id) = shared::people().get(&(self.tracker(), name.to_owned())) {
return Ok(id.clone());
}
Err(SourceError::Refused {
message: format!(
"Linear holds no user displayed as {name:?} in the workspace source {} reads; \
next: name the person by their Linear display name, exactly as Linear spells \
it, or leave the task unassigned",
self.name
),
})
}
pub(crate) fn forget_people(&self) {
*self
.forget_at_end
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) = true;
}
pub(crate) fn forget_people_at_end_of_call(&self) {
let due = std::mem::take(
&mut *self
.forget_at_end
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner),
);
if due {
let tracker = self.tracker();
shared::people().retain(|(held, _), _| *held != tracker);
self.unknown().clear();
}
}
pub(crate) fn forget_unknown_people(&self) {
self.unknown().clear();
}
fn unknown(&self) -> std::sync::MutexGuard<'_, std::collections::BTreeSet<String>> {
self.unknown_people
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
pub(crate) fn assigned_as(
&self,
id: &NativeId,
asked: Option<&[String]>,
task: &Task,
) -> Result<(), SourceError> {
self.answered_as(id, asked, task.assignees.as_deref().unwrap_or_default())
}
pub(crate) fn answered_as(
&self,
id: &NativeId,
asked: Option<&[String]>,
answered: &[String],
) -> Result<(), SourceError> {
let Some(asked) = asked else {
return Ok(());
};
if answered == asked {
return Ok(());
}
self.forget_people();
let said = |people: &[String]| match people {
[] => "nobody".to_owned(),
people => people
.iter()
.map(|person| format!("{person:?}"))
.collect::<Vec<_>>()
.join(", "),
};
Err(SourceError::Refused {
message: format!(
"Linear answered the write of task {id} on source {} as assigned to {} where it \
was asked to assign {}; next: read the task, and set its assignee again",
self.name,
said(answered),
said(asked)
),
})
}
}
#[cfg(test)]
mod tests {
use super::{PEOPLE_PER_LOOKUP, USERS_CONNECTIONS, USERS_PAGE};
#[test]
fn the_readme_states_the_lookup_limit_this_plugin_splits_at() {
let readme = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../README.md"));
let per_connection = 1 + 1 + USERS_PAGE * 12 / 10;
assert!(per_connection * USERS_CONNECTIONS <= 10_000);
assert!(per_connection * (USERS_CONNECTIONS + 1) > 10_000);
let row = format!(
"| `linear` | {},{:03} display names | {USERS_CONNECTIONS} `users` connections of \
{USERS_PAGE} (Linear's connection maximum), each at most {per_connection} of the \
10,000 complexity points Linear allows a query |",
PEOPLE_PER_LOOKUP / 1000,
PEOPLE_PER_LOOKUP % 1000
);
assert!(readme.contains(&row), "the README states {row:?}");
}
}