summaryrefslogtreecommitdiff
path: root/ext/broadcast_channel/lib.rs
blob: c1de118a364fad283fdd9a259b18c08e5bb64ee8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.

mod in_memory_broadcast_channel;

pub use in_memory_broadcast_channel::InMemoryBroadcastChannel;
pub use in_memory_broadcast_channel::InMemoryBroadcastChannelResource;

use std::cell::RefCell;
use std::path::PathBuf;
use std::rc::Rc;

use async_trait::async_trait;
use deno_core::op2;
use deno_core::JsBuffer;
use deno_core::OpState;
use deno_core::Resource;
use deno_core::ResourceId;
use tokio::sync::broadcast::error::SendError as BroadcastSendError;
use tokio::sync::mpsc::error::SendError as MpscSendError;

pub const UNSTABLE_FEATURE_NAME: &str = "broadcast-channel";

#[derive(Debug, thiserror::Error)]
pub enum BroadcastChannelError {
  #[error(transparent)]
  Resource(deno_core::error::AnyError),
  #[error(transparent)]
  MPSCSendError(MpscSendError<Box<dyn std::fmt::Debug + Send + Sync>>),
  #[error(transparent)]
  BroadcastSendError(
    BroadcastSendError<Box<dyn std::fmt::Debug + Send + Sync>>,
  ),
  #[error(transparent)]
  Other(deno_core::error::AnyError),
}

impl<T: std::fmt::Debug + Send + Sync + 'static> From<MpscSendError<T>>
  for BroadcastChannelError
{
  fn from(value: MpscSendError<T>) -> Self {
    BroadcastChannelError::MPSCSendError(MpscSendError(Box::new(value.0)))
  }
}
impl<T: std::fmt::Debug + Send + Sync + 'static> From<BroadcastSendError<T>>
  for BroadcastChannelError
{
  fn from(value: BroadcastSendError<T>) -> Self {
    BroadcastChannelError::BroadcastSendError(BroadcastSendError(Box::new(
      value.0,
    )))
  }
}

#[async_trait]
pub trait BroadcastChannel: Clone {
  type Resource: Resource;

  fn subscribe(&self) -> Result<Self::Resource, BroadcastChannelError>;

  fn unsubscribe(
    &self,
    resource: &Self::Resource,
  ) -> Result<(), BroadcastChannelError>;

  async fn send(
    &self,
    resource: &Self::Resource,
    name: String,
    data: Vec<u8>,
  ) -> Result<(), BroadcastChannelError>;

  async fn recv(
    &self,
    resource: &Self::Resource,
  ) -> Result<Option<Message>, BroadcastChannelError>;
}

pub type Message = (String, Vec<u8>);

#[op2(fast)]
#[smi]
pub fn op_broadcast_subscribe<BC>(
  state: &mut OpState,
) -> Result<ResourceId, BroadcastChannelError>
where
  BC: BroadcastChannel + 'static,
{
  state
    .feature_checker
    .check_or_exit(UNSTABLE_FEATURE_NAME, "BroadcastChannel");
  let bc = state.borrow::<BC>();
  let resource = bc.subscribe()?;
  Ok(state.resource_table.add(resource))
}

#[op2(fast)]
pub fn op_broadcast_unsubscribe<BC>(
  state: &mut OpState,
  #[smi] rid: ResourceId,
) -> Result<(), BroadcastChannelError>
where
  BC: BroadcastChannel + 'static,
{
  let resource = state
    .resource_table
    .get::<BC::Resource>(rid)
    .map_err(BroadcastChannelError::Resource)?;
  let bc = state.borrow::<BC>();
  bc.unsubscribe(&resource)
}

#[op2(async)]
pub async fn op_broadcast_send<BC>(
  state: Rc<RefCell<OpState>>,
  #[smi] rid: ResourceId,
  #[string] name: String,
  #[buffer] buf: JsBuffer,
) -> Result<(), BroadcastChannelError>
where
  BC: BroadcastChannel + 'static,
{
  let resource = state
    .borrow()
    .resource_table
    .get::<BC::Resource>(rid)
    .map_err(BroadcastChannelError::Resource)?;
  let bc = state.borrow().borrow::<BC>().clone();
  bc.send(&resource, name, buf.to_vec()).await
}

#[op2(async)]
#[serde]
pub async fn op_broadcast_recv<BC>(
  state: Rc<RefCell<OpState>>,
  #[smi] rid: ResourceId,
) -> Result<Option<Message>, BroadcastChannelError>
where
  BC: BroadcastChannel + 'static,
{
  let resource = state
    .borrow()
    .resource_table
    .get::<BC::Resource>(rid)
    .map_err(BroadcastChannelError::Resource)?;
  let bc = state.borrow().borrow::<BC>().clone();
  bc.recv(&resource).await
}

deno_core::extension!(deno_broadcast_channel,
  deps = [ deno_webidl, deno_web ],
  parameters = [BC: BroadcastChannel],
  ops = [
    op_broadcast_subscribe<BC>,
    op_broadcast_unsubscribe<BC>,
    op_broadcast_send<BC>,
    op_broadcast_recv<BC>,
  ],
  esm = [ "01_broadcast_channel.js" ],
  options = {
    bc: BC,
  },
  state = |state, options| {
    state.put(options.bc);
  },
);

pub fn get_declaration() -> PathBuf {
  PathBuf::from(env!("CARGO_MANIFEST_DIR"))
    .join("lib.deno_broadcast_channel.d.ts")
}