Skip to content
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

chore: simplify the code #147

Merged
merged 5 commits into from
May 31, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
69 changes: 37 additions & 32 deletions arroyo-api/src/optimizations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ pub fn optimize(graph: &mut DiGraph<StreamNode, StreamEdge>) {

fn remove_in_place(graph: &mut DiGraph<StreamNode, StreamEdge>, node: NodeIndex) {
let incoming = graph
.edges_directed(node, Direction::Incoming)
.edges_directed(node, Incoming)
.next()
.unwrap();

Expand All @@ -30,7 +30,7 @@ fn remove_in_place(graph: &mut DiGraph<StreamNode, StreamEdge>, node: NodeIndex)
graph.remove_edge(incoming);

let outgoing: Vec<_> = graph
.edges_directed(node, Direction::Outgoing)
.edges_directed(node, Outgoing)
.map(|e| (e.id(), e.target().id()))
.collect();

Expand All @@ -44,39 +44,43 @@ fn remove_in_place(graph: &mut DiGraph<StreamNode, StreamEdge>, node: NodeIndex)

fn fuse_window_aggregation(graph: &mut DiGraph<StreamNode, StreamEdge>) {
'outer: loop {
let sources: Vec<_> = graph.externals(Direction::Incoming).collect();
let sources: Vec<_> = graph.externals(Incoming).collect();

for source in sources {
let mut dfs = Dfs::new(&(*graph), source);

while let Some(idx) = dfs.next(&(*graph)) {
let operator = graph.node_weight(idx).unwrap().operator.clone();
let mut ins = graph.edges_directed(idx, Direction::Incoming);
let mut ins = graph.edges_directed(idx, Incoming);

let in_degree = ins.clone().count();
let no_shuffles = ins.all(|e| e.weight().typ == EdgeType::Forward);

let mut ins = graph.edges_directed(idx, Direction::Incoming);
if no_shuffles && in_degree == 1 {
let source_idx = ins.next().unwrap().source();
let in_node = graph.node_weight_mut(source_idx).unwrap();
if let Operator::Window { agg, .. } = &mut in_node.operator {
if agg.is_none() {
let new_agg = match &operator {
Operator::Count => Some(WindowAgg::Count),
Operator::Aggregate(AggregateBehavior::Min) => Some(WindowAgg::Min),
Operator::Aggregate(AggregateBehavior::Max) => Some(WindowAgg::Max),
Operator::Aggregate(AggregateBehavior::Sum) => Some(WindowAgg::Sum),
_ => None,
};

if let Some(new_agg) = new_agg {
*agg = Some(new_agg);
remove_in_place(graph, idx);
// restart the loop if we change something
continue 'outer;
}
}
let mut ins = graph.edges_directed(idx, Incoming);
if !(no_shuffles && in_degree == 1) {
continue;
}

let source_idx = ins.next().unwrap().source();
let in_node = graph.node_weight_mut(source_idx).unwrap();
if let Operator::Window { agg, .. } = &mut in_node.operator {
if !agg.is_none() {
chenquan marked this conversation as resolved.
Show resolved Hide resolved
continue;
}

let new_agg = match &operator {
Operator::Count => Some(WindowAgg::Count),
Operator::Aggregate(AggregateBehavior::Min) => Some(WindowAgg::Min),
Operator::Aggregate(AggregateBehavior::Max) => Some(WindowAgg::Max),
Operator::Aggregate(AggregateBehavior::Sum) => Some(WindowAgg::Sum),
_ => None,
};

if let Some(new_agg) = new_agg {
*agg = Some(new_agg);
remove_in_place(graph, idx);
// restart the loop if we change something
continue 'outer;
}
}
}
Expand All @@ -95,13 +99,13 @@ pub trait Optimizer {

fn optimize_once(&self, graph: &mut DiGraph<StreamNode, StreamEdge>) -> bool {
let mut to_fuse = vec![vec![]];
for source in graph.externals(Direction::Incoming) {
for source in graph.externals(Incoming) {
let mut dfs = Dfs::new(&(*graph), source);
let mut current_chain = vec![];

while let Some(idx) = dfs.next(&(*graph)) {
let node = graph.node_weight(idx).unwrap();
let mut ins = graph.edges_directed(idx, Direction::Incoming);
let mut ins = graph.edges_directed(idx, Incoming);

let in_degree = ins.clone().count();
let no_shuffles = ins.all(|e| e.weight().typ == EdgeType::Forward);
Expand Down Expand Up @@ -241,8 +245,8 @@ impl FusedExpressionOperatorBuilder {
let body = quote!(
{#(#fused_body_tokens)*
#return_value
})
.to_string();
}).to_string();

let expr: syn::Expr = parse_str(&body).expect(&body);
let expression = quote!(#expr).to_string();
Operator::ExpressionOperator {
Expand All @@ -261,9 +265,9 @@ impl FusedExpressionOperatorBuilder {
) -> bool {
let out_type = format!("arroyo_types::Record<{},{}>", edge.key, edge.value);
match return_type {
ExpressionReturnType::Predicate => self.fuse_predicate(name, expression),
ExpressionReturnType::Record => self.fuse_map(name, expression, out_type),
ExpressionReturnType::OptionalRecord => {
Predicate => self.fuse_predicate(name, expression),
Record => self.fuse_map(name, expression, out_type),
OptionalRecord => {
self.fuse_option_map(name, expression, out_type)
}
}
Expand Down Expand Up @@ -395,6 +399,7 @@ impl Optimizer for FlatMapFusionOptimizer {
}

struct WasmFusionOptimizer {}

impl Optimizer for WasmFusionOptimizer {
fn can_optimize(&self, node: &StreamNode, _current_chain: &[StreamNode]) -> bool {
matches!(&node.operator, Operator::FusedWasmUDFs { .. })
Expand Down
16 changes: 8 additions & 8 deletions arroyo-api/src/pipelines.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ async fn compile_sql<'e, E>(
auth_data: &AuthData,
tx: &E,
) -> Result<(Program, Vec<i64>, Vec<i64>), Status>
where
E: GenericClient,
where
E: GenericClient,
{
let mut schema_provider = ArroyoSchemaProvider::new();

Expand Down Expand Up @@ -104,12 +104,12 @@ where
kafka_qps: Some(auth_data.org_metadata.kafka_qps),
},
)
.await
.with_context(|| "failed to generate SQL program")
.map_err(|err| {
warn!("{:?}", err);
Status::invalid_argument(format!("{}", err.root_cause()))
})?;
.await
.with_context(|| "failed to generate SQL program")
.map_err(|err| {
warn!("{:?}", err);
Status::invalid_argument(format!("{}", err.root_cause()))
})?;

Ok((program, sources, used_sink_ids))
}
Expand Down
40 changes: 20 additions & 20 deletions arroyo-api/src/sources.rs
Original file line number Diff line number Diff line change
Expand Up @@ -350,16 +350,16 @@ fn builtin_for_name(name: &str) -> Result<SourceSchema, String> {
impl SourceSchema {
pub fn try_from(name: &str, s: api::SourceSchema) -> Result<Self, String> {
match s.schema.unwrap() {
api::source_schema::Schema::Builtin(name) => builtin_for_name(&name),
api::source_schema::Schema::JsonSchema(def) => {
Schema::Builtin(name) => builtin_for_name(&name),
Schema::JsonSchema(def) => {
let fields = json_schema::convert_json_schema(name, &def.json_schema)?;
Ok(SourceSchema {
format: SourceFormat::JsonSchema(def.json_schema),
fields,
kafka_schema: s.kafka_schema_registry,
})
}
api::source_schema::Schema::JsonFields(def) => {
Schema::JsonFields(def) => {
let fields: Result<Vec<_>, String> =
def.fields.into_iter().map(|f| f.try_into()).collect();
Ok(SourceSchema {
Expand All @@ -369,7 +369,7 @@ impl SourceSchema {
})
}
Schema::RawJson(_) => Ok(raw_schema()),
api::source_schema::Schema::Protobuf(_) => {
Schema::Protobuf(_) => {
Err("protobuf not supported yet".to_string())
}
}
Expand All @@ -396,9 +396,9 @@ impl TryFrom<&SourceSchema> for api::SourceSchema {
fn try_from(s: &SourceSchema) -> Result<Self, Self::Error> {
Ok(api::SourceSchema {
schema: Some(match &s.format {
SourceFormat::Native(s) => api::source_schema::Schema::Builtin(s.clone()),
SourceFormat::Native(s) => Schema::Builtin(s.clone()),
SourceFormat::JsonFields => {
api::source_schema::Schema::JsonFields(api::JsonFieldDef {
Schema::JsonFields(api::JsonFieldDef {
fields: s
.fields
.clone()
Expand All @@ -408,11 +408,11 @@ impl TryFrom<&SourceSchema> for api::SourceSchema {
})
}
SourceFormat::JsonSchema(s) => {
api::source_schema::Schema::JsonSchema(JsonSchemaDef {
Schema::JsonSchema(JsonSchemaDef {
json_schema: s.clone(),
})
}
SourceFormat::RawJson => api::source_schema::Schema::RawJson(api::RawJsonDef {}),
SourceFormat::RawJson => Schema::RawJson(api::RawJsonDef {}),
}),
kafka_schema_registry: s.kafka_schema,
})
Expand All @@ -430,7 +430,7 @@ impl TryFrom<SourceDef> for Source {
type Error = String;

fn try_from(value: SourceDef) -> Result<Self, Self::Error> {
let schema = if let api::source_schema::Schema::Builtin(name) =
let schema = if let Schema::Builtin(name) =
value.schema.as_ref().unwrap().schema.as_ref().unwrap()
{
builtin_for_name(name)?
Expand Down Expand Up @@ -496,7 +496,7 @@ pub(crate) async fn create_source(
req: CreateSourceReq,
auth: AuthData,
pool: &Pool,
) -> core::result::Result<(), Status> {
) -> Result<(), Status> {
let schema_name = format!("{}_schema", req.name);

let mut c = pool.get().await.map_err(log_and_map)?;
Expand All @@ -518,13 +518,13 @@ pub(crate) async fn create_source(
.or_else(|| {
match req.type_oneof {
Some(create_source_req::TypeOneof::Impulse { .. }) => {
Some(source_schema::Schema::Builtin("impulse".to_string()))
Some(Schema::Builtin("impulse".to_string()))
}
Some(create_source_req::TypeOneof::Nexmark { .. }) => {
Some(source_schema::Schema::Builtin("nexmark".to_string()))
Some(Schema::Builtin("nexmark".to_string()))
}
Some(create_source_req::TypeOneof::Kafka { .. }) => {
Some(source_schema::Schema::RawJson(RawJsonDef {}))
Some(Schema::RawJson(RawJsonDef {}))
}
_ => None,
}
Expand All @@ -539,25 +539,25 @@ pub(crate) async fn create_source(
.schema
.ok_or_else(|| required_field("schema.schema"))?
{
source_schema::Schema::Builtin(name) => {
Schema::Builtin(name) => {
builtin_for_name(&name).map_err(Status::invalid_argument)?;
(SchemaType::builtin, serde_json::to_value(&name).unwrap())
}
source_schema::Schema::JsonSchema(js) => {
Schema::JsonSchema(js) => {
// try to convert the schema to ensure it's valid
convert_json_schema(&req.name, &js.json_schema).map_err(Status::invalid_argument)?;

// parse the schema into a value
(SchemaType::json_schema, serde_json::to_value(&js).unwrap())
}
source_schema::Schema::JsonFields(fields) => (
Schema::JsonFields(fields) => (
SchemaType::json_fields,
serde_json::to_value(fields).unwrap(),
),
source_schema::Schema::RawJson(_) => {
Schema::RawJson(_) => {
(SchemaType::raw_json, serde_json::to_value(()).unwrap())
}
source_schema::Schema::Protobuf(_) => todo!(),
Schema::Protobuf(_) => todo!(),
};

let schema_id = api_queries::create_schema()
Expand Down Expand Up @@ -771,7 +771,7 @@ pub(crate) async fn test_schema(req: CreateSourceReq) -> Result<Vec<String>, Sta

match schema {
Schema::JsonSchema(schema) => {
if let Err(e) = json_schema::convert_json_schema(&req.name, &schema.json_schema) {
if let Err(e) = convert_json_schema(&req.name, &schema.json_schema) {
Ok(vec![e])
} else {
Ok(vec![])
Expand Down Expand Up @@ -962,7 +962,7 @@ pub(crate) async fn get_confluent_schema(
)
})?;

if let Err(e) = json_schema::convert_json_schema(&req.topic, schema) {
if let Err(e) = convert_json_schema(&req.topic, schema) {
warn!(
"Schema from schema registry is not valid: '{}': {}",
schema, e
Expand Down