Skip to content

General cleanup and fixes: pubsub #12

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 2, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 31 additions & 27 deletions src/CoreApi/PubSubApi.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Multiformats.Base;

namespace Ipfs.Http
{
Expand All @@ -21,7 +22,7 @@ internal PubSubApi(IpfsClient ipfs)
this.ipfs = ipfs;
}

public async Task<IEnumerable<string>> SubscribedTopicsAsync(CancellationToken cancel = default(CancellationToken))
public async Task<IEnumerable<string>> SubscribedTopicsAsync(CancellationToken cancel = default)
{
var json = await ipfs.DoCommandAsync("pubsub/ls", cancel);
var result = JObject.Parse(json);
Expand All @@ -30,68 +31,71 @@ internal PubSubApi(IpfsClient ipfs)
return strings.Select(s => (string)s);
}

public async Task<IEnumerable<Peer>> PeersAsync(string topic = null, CancellationToken cancel = default(CancellationToken))
public async Task<IEnumerable<Peer>> PeersAsync(string topic = null, CancellationToken cancel = default)
{
var json = await ipfs.DoCommandAsync("pubsub/peers", cancel, topic);
var result = JObject.Parse(json);
var strings = result["Strings"] as JArray;
if (strings == null) return new Peer[0];

if (strings == null)
return Array.Empty<Peer>();

return strings.Select(s => new Peer { Id = (string)s });
}

public Task PublishAsync(string topic, byte[] message, CancellationToken cancel = default(CancellationToken))
public Task PublishAsync(string topic, byte[] message, CancellationToken cancel = default)
{
var url = new StringBuilder();
url.Append("/api/v0/pubsub/pub");
url.Append("?arg=");
url.Append(System.Net.WebUtility.UrlEncode(topic));
url.Append("&arg=");
var data = Encoding.ASCII.GetString(System.Net.WebUtility.UrlEncodeToBytes(message, 0, message.Length));
url.Append(data);
return ipfs.DoCommandAsync(new Uri(ipfs.ApiUri, url.ToString()), cancel);
url.Append("?arg=u");
url.Append(Multibase.Encode(MultibaseEncoding.Base64Url, Encoding.UTF8.GetBytes(topic)));

return ipfs.DoCommandAsync(new Uri(ipfs.ApiUri, url.ToString()), message, cancel);
}

public Task PublishAsync(string topic, Stream message, CancellationToken cancel = default(CancellationToken))
public Task PublishAsync(string topic, Stream message, CancellationToken cancel = default)
{
using (MemoryStream ms = new MemoryStream())
{
message.CopyTo(ms);
return PublishAsync(topic, ms.ToArray(), cancel);
}
var url = new StringBuilder();
url.Append("/api/v0/pubsub/pub");
url.Append("?arg=u");
url.Append(Multibase.Encode(MultibaseEncoding.Base64Url, Encoding.UTF8.GetBytes(topic)));

return ipfs.DoCommandAsync(new Uri(ipfs.ApiUri, url.ToString()), message, cancel);
}

public async Task PublishAsync(string topic, string message, CancellationToken cancel = default(CancellationToken))
public async Task PublishAsync(string topic, string message, CancellationToken cancel = default)
{
var _ = await ipfs.DoCommandAsync("pubsub/pub", cancel, topic, "arg=" + message);
return;
var url = new StringBuilder();
url.Append("/api/v0/pubsub/pub");
url.Append("?arg=u");
url.Append(Multibase.Encode(MultibaseEncoding.Base64Url, Encoding.UTF8.GetBytes(topic)));

await ipfs.DoCommandAsync(new Uri(ipfs.ApiUri, url.ToString()), message, cancel);
}

public async Task SubscribeAsync(string topic, Action<IPublishedMessage> handler, CancellationToken cancellationToken)
{
var messageStream = await ipfs.PostDownloadAsync("pubsub/sub", cancellationToken, topic);
var messageStream = await ipfs.PostDownloadAsync("pubsub/sub", cancellationToken, $"u{Multibase.Encode(MultibaseEncoding.Base64Url, Encoding.UTF8.GetBytes(topic))}");
var sr = new StreamReader(messageStream);

#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
Task.Run(() => ProcessMessages(topic, handler, sr, cancellationToken));
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed

return;
_ = Task.Run(() => ProcessMessages(topic, handler, sr, cancellationToken), cancellationToken);
}

void ProcessMessages(string topic, Action<PublishedMessage> handler, StreamReader sr, CancellationToken ct)
{
log.DebugFormat("Start listening for '{0}' messages", topic);
log.DebugFormat($"Start listening for '{topic}' messages");

// .Net needs a ReadLine(CancellationToken)
// As a work-around, we register a function to close the stream
ct.Register(() => sr.Dispose());
ct.Register(sr.Dispose);
try
{
while (!sr.EndOfStream && !ct.IsCancellationRequested)
{
var json = sr.ReadLine();
if (json == null)
break;

if (log.IsDebugEnabled)
log.DebugFormat("PubSub message {0}", json);

Expand Down
104 changes: 80 additions & 24 deletions src/IpfsClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,7 @@ namespace Ipfs.Http
/// <seealso href="https://ipfs.io/docs/api/">IPFS API</seealso>
/// <seealso href="https://ipfs.io/docs/commands/">IPFS commands</seealso>
/// <remarks>
/// <b>IpfsClient</b> is thread safe, only one instance is required
/// by the application.
/// <b>IpfsClient</b> is thread safe, only one instance is required by the application.
/// </remarks>
public partial class IpfsClient : ICoreApi
{
Expand Down Expand Up @@ -61,6 +60,7 @@ public IpfsClient()

var assembly = typeof(IpfsClient).GetTypeInfo().Assembly;
var version = assembly.GetName().Version;

UserAgent = string.Format("{0}/{1}.{2}.{3}", assembly.GetName().Name, version.Major, version.Minor, version.Revision);
TrustedPeers = new TrustedPeerCollection(this);

Expand Down Expand Up @@ -115,7 +115,7 @@ public IpfsClient(string host)
/// The list of peers that are initially trusted by IPFS.
/// </summary>
/// <remarks>
/// This is equilivent to <c>ipfs bootstrap list</c>.
/// This is equivalent to <c>ipfs bootstrap list</c>.
/// </remarks>
public TrustedPeerCollection TrustedPeers { get; private set; }

Expand Down Expand Up @@ -174,6 +174,7 @@ Uri BuildCommand(string command, string arg = null, params string[] options)
{
var url = "/api/v0/" + command;
var q = new StringBuilder();

if (arg != null)
{
q.Append("&arg=");
Expand Down Expand Up @@ -223,23 +224,29 @@ HttpClient Api()
{
if (api == null)
{
var handler = new HttpClientHandler();
if (handler.SupportsAutomaticDecompression)
if (HttpMessageHandler is HttpClientHandler handler && handler.SupportsAutomaticDecompression)
{
handler.AutomaticDecompression = DecompressionMethods.GZip
| DecompressionMethods.Deflate;
}
api = new HttpClient(handler)

api = new HttpClient(HttpMessageHandler)
{
Timeout = System.Threading.Timeout.InfiniteTimeSpan
Timeout = Timeout.InfiniteTimeSpan
};

api.DefaultRequestHeaders.Add("User-Agent", UserAgent);
}
}
}
return api;
}

/// <summary>
/// The message handler to use for communicating over HTTP.
/// </summary>
public HttpMessageHandler HttpMessageHandler { get; set; } = new HttpClientHandler();

/// <summary>
/// Perform an <see href="https://ipfs.io/docs/api/">IPFS API command</see> returning a string.
/// </summary>
Expand All @@ -265,29 +272,49 @@ HttpClient Api()
public async Task<string> DoCommandAsync(string command, CancellationToken cancel, string arg = null, params string[] options)
{
var url = BuildCommand(command, arg, options);

if (log.IsDebugEnabled)
log.Debug("POST " + url.ToString());
log.Debug("POST " + url);

using (var response = await Api().PostAsync(url, null, cancel))
{
await ThrowOnErrorAsync(response);
var body = await response.Content.ReadAsStringAsync();

if (log.IsDebugEnabled)
log.Debug("RSP " + body);

return body;
}
}

internal async Task DoCommandAsync(Uri url, CancellationToken cancel)
internal Task DoCommandAsync(Uri url, byte[] bytes, CancellationToken cancel)
{
return DoCommandAsync(url, new ByteArrayContent(bytes), cancel);
}

internal Task DoCommandAsync(Uri url, Stream stream, CancellationToken cancel)
{
return DoCommandAsync(url, new StreamContent(stream), cancel);
}

internal Task DoCommandAsync(Uri url, string str, CancellationToken cancel)
{
return DoCommandAsync(url, new StringContent(str), cancel);
}

internal async Task DoCommandAsync(Uri url, HttpContent content, CancellationToken cancel)
{
if (log.IsDebugEnabled)
log.Debug("POST " + url.ToString());
using (var response = await Api().PostAsync(url, null, cancel))
log.Debug("POST " + url);

using (var response = await Api().PostAsync(url, new MultipartFormDataContent { { content, "\"file\"" } }, cancel))
{
await ThrowOnErrorAsync(response);
var body = await response.Content.ReadAsStringAsync();

if (log.IsDebugEnabled)
log.Debug("RSP " + body);
return;
}
}

Expand Down Expand Up @@ -353,12 +380,15 @@ public async Task<T> DoCommandAsync<T>(string command, CancellationToken cancel,
public async Task<Stream> PostDownloadAsync(string command, CancellationToken cancel, string arg = null, params string[] options)
{
var url = BuildCommand(command, arg, options);

if (log.IsDebugEnabled)
log.Debug("POST " + url.ToString());
var request = new HttpRequestMessage(HttpMethod.Post, url);
log.Debug("POST " + url);

var request = new HttpRequestMessage(HttpMethod.Post, url);
var response = await Api().SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancel);

await ThrowOnErrorAsync(response);

return await response.Content.ReadAsStreamAsync();
}

Expand Down Expand Up @@ -388,10 +418,13 @@ public async Task<Stream> PostDownloadAsync(string command, CancellationToken ca
public async Task<Stream> DownloadAsync(string command, CancellationToken cancel, string arg = null, params string[] options)
{
var url = BuildCommand(command, arg, options);

if (log.IsDebugEnabled)
log.Debug("GET " + url.ToString());
log.Debug("GET " + url);

var response = await Api().GetAsync(url, HttpCompletionOption.ResponseHeadersRead, cancel);
await ThrowOnErrorAsync(response);

return await response.Content.ReadAsStreamAsync();
}

Expand Down Expand Up @@ -421,10 +454,13 @@ public async Task<Stream> DownloadAsync(string command, CancellationToken cancel
public async Task<byte[]> DownloadBytesAsync(string command, CancellationToken cancel, string arg = null, params string[] options)
{
var url = BuildCommand(command, arg, options);

if (log.IsDebugEnabled)
log.Debug("GET " + url.ToString());
log.Debug("GET " + url);

var response = await Api().GetAsync(url, HttpCompletionOption.ResponseHeadersRead, cancel);
await ThrowOnErrorAsync(response);

return await response.Content.ReadAsByteArrayAsync();
}

Expand Down Expand Up @@ -460,21 +496,26 @@ public async Task<String> UploadAsync(string command, CancellationToken cancel,
{
var content = new MultipartFormDataContent();
var streamContent = new StreamContent(data);

streamContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

if (string.IsNullOrEmpty(name))
content.Add(streamContent, "file", unknownFilename);
else
content.Add(streamContent, "file", name);

var url = BuildCommand(command, null, options);
if (log.IsDebugEnabled)
log.Debug("POST " + url.ToString());
log.Debug("POST " + url);

using (var response = await Api().PostAsync(url, content, cancel))
{
await ThrowOnErrorAsync(response);
var json = await response.Content.ReadAsStringAsync();

if (log.IsDebugEnabled)
log.Debug("RSP " + json);

return json;
}
}
Expand Down Expand Up @@ -510,17 +551,19 @@ public async Task<Stream> Upload2Async(string command, CancellationToken cancel,
{
var content = new MultipartFormDataContent();
var streamContent = new StreamContent(data);

streamContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
if (string.IsNullOrEmpty(name))
content.Add(streamContent, "file", unknownFilename);
else
content.Add(streamContent, "file", name);

content.Add(streamContent, "file", string.IsNullOrEmpty(name) ? unknownFilename : name);

var url = BuildCommand(command, null, options);

if (log.IsDebugEnabled)
log.Debug("POST " + url.ToString());
log.Debug("POST " + url);

var response = await Api().PostAsync(url, content, cancel);
await ThrowOnErrorAsync(response);

return await response.Content.ReadAsStreamAsync();
}

Expand All @@ -531,18 +574,24 @@ public async Task<String> UploadAsync(string command, CancellationToken cancel,
{
var content = new MultipartFormDataContent();
var streamContent = new ByteArrayContent(data);

streamContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
content.Add(streamContent, "file", unknownFilename);

var url = BuildCommand(command, null, options);

if (log.IsDebugEnabled)
log.Debug("POST " + url.ToString());
log.Debug("POST " + url);

using (var response = await Api().PostAsync(url, content, cancel))
{
await ThrowOnErrorAsync(response);

var json = await response.Content.ReadAsStringAsync();

if (log.IsDebugEnabled)
log.Debug("RSP " + json);

return json;
}
}
Expand All @@ -562,24 +611,31 @@ async Task<bool> ThrowOnErrorAsync(HttpResponseMessage response)
{
if (response.IsSuccessStatusCode)
return true;

if (response.StatusCode == HttpStatusCode.NotFound)
{
var error = "Invalid IPFS command: " + response.RequestMessage.RequestUri.ToString();
var error = "Invalid IPFS command: " + response.RequestMessage.RequestUri;

if (log.IsDebugEnabled)
log.Debug("ERR " + error);

throw new HttpRequestException(error);
}

var body = await response.Content.ReadAsStringAsync();

if (log.IsDebugEnabled)
log.Debug("ERR " + body);

string message = body;

try
{
var res = JsonConvert.DeserializeObject<dynamic>(body);
message = (string)res.Message;
}
catch { }

throw new HttpRequestException(message);
}

Expand Down
Loading