Skip to main content

spin_factor_outbound_mysql/
lib.rs

1pub mod client;
2mod host;
3
4use client::Client;
5use mysql_async::Conn as MysqlClient;
6use spin_factor_otel::OtelFactorState;
7use spin_factor_outbound_networking::{
8    config::allowed_hosts::OutboundAllowedHosts, OutboundNetworkingFactor,
9};
10use spin_factors::{Factor, FactorData, InitContext, RuntimeFactors, SelfInstanceBuilder};
11use spin_world::v1::mysql as v1;
12use spin_world::v2::mysql::{self as v2};
13
14pub struct OutboundMysqlFactor<C = MysqlClient> {
15    _phantom: std::marker::PhantomData<C>,
16}
17
18impl<C: Send + Sync + Client + 'static> Factor for OutboundMysqlFactor<C> {
19    type RuntimeConfig = ();
20    type AppState = ();
21    type InstanceBuilder = InstanceState<C>;
22
23    fn init(&mut self, ctx: &mut impl InitContext<Self>) -> anyhow::Result<()> {
24        ctx.link_bindings(v1::add_to_linker::<_, FactorData<Self>>)?;
25        ctx.link_bindings(v2::add_to_linker::<_, FactorData<Self>>)?;
26        Ok(())
27    }
28
29    fn configure_app<T: RuntimeFactors>(
30        &self,
31        _ctx: spin_factors::ConfigureAppContext<T, Self>,
32    ) -> anyhow::Result<Self::AppState> {
33        Ok(())
34    }
35
36    fn prepare<T: spin_factors::RuntimeFactors>(
37        &self,
38        mut ctx: spin_factors::PrepareContext<T, Self>,
39    ) -> anyhow::Result<Self::InstanceBuilder> {
40        let allowed_hosts = ctx
41            .instance_builder::<OutboundNetworkingFactor>()?
42            .allowed_hosts();
43        let otel = OtelFactorState::from_prepare_context(&mut ctx)?;
44
45        Ok(InstanceState {
46            allowed_hosts,
47            connections: Default::default(),
48            otel,
49        })
50    }
51}
52
53impl<C> Default for OutboundMysqlFactor<C> {
54    fn default() -> Self {
55        Self {
56            _phantom: Default::default(),
57        }
58    }
59}
60
61impl<C> OutboundMysqlFactor<C> {
62    pub fn new() -> Self {
63        Self::default()
64    }
65}
66
67pub struct InstanceState<C> {
68    allowed_hosts: OutboundAllowedHosts,
69    connections: spin_resource_table::Table<C>,
70    otel: OtelFactorState,
71}
72
73impl<C: Send + 'static> SelfInstanceBuilder for InstanceState<C> {}