spin_factor_outbound_pg/
lib.rs

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