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<T: Send + 'static>(
21        &mut self,
22        mut ctx: spin_factors::InitContext<T, Self>,
23    ) -> anyhow::Result<()> {
24        ctx.link_bindings(spin_world::v1::postgres::add_to_linker)?;
25        ctx.link_bindings(spin_world::v2::postgres::add_to_linker)?;
26        ctx.link_bindings(spin_world::spin::postgres::postgres::add_to_linker)?;
27        Ok(())
28    }
29
30    fn configure_app<T: RuntimeFactors>(
31        &self,
32        _ctx: ConfigureAppContext<T, Self>,
33    ) -> anyhow::Result<Self::AppState> {
34        Ok(())
35    }
36
37    fn prepare<T: RuntimeFactors>(
38        &self,
39        mut ctx: PrepareContext<T, Self>,
40    ) -> anyhow::Result<Self::InstanceBuilder> {
41        let allowed_hosts = ctx
42            .instance_builder::<OutboundNetworkingFactor>()?
43            .allowed_hosts();
44        Ok(InstanceState {
45            allowed_hosts,
46            connections: Default::default(),
47        })
48    }
49}
50
51impl<C> Default for OutboundPgFactor<C> {
52    fn default() -> Self {
53        Self {
54            _phantom: Default::default(),
55        }
56    }
57}
58
59impl<C> OutboundPgFactor<C> {
60    pub fn new() -> Self {
61        Self::default()
62    }
63}
64
65pub struct InstanceState<C> {
66    allowed_hosts: OutboundAllowedHosts,
67    connections: spin_resource_table::Table<C>,
68}
69
70impl<C: Send + 'static> SelfInstanceBuilder for InstanceState<C> {}