spin_factor_outbound_pg/
lib.rs

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