forked from PrimalZed/CloudSync
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SftpContextAccessor.cs
37 lines (30 loc) · 1.12 KB
/
SftpContextAccessor.cs
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
using PrimalZed.CloudSync.Interop;
using PrimalZed.CloudSync.Remote.Abstractions;
namespace PrimalZed.CloudSync.Remote.Sftp;
public interface ISftpContextAccessor {
SftpContext Context { get; }
}
public class SftpContextAccessor : IRemoteContextSetter, ISftpContextAccessor {
private static readonly AsyncLocal<ContextHolder> _sftpContextCurrent = new();
public string RemoteKind => SftpConstants.KIND;
/// <inheritdoc/>
public SftpContext Context {
get => _sftpContextCurrent.Value?.Context! ?? throw new NullReferenceException();
set {
var holder = _sftpContextCurrent.Value;
if (holder != null) {
// Clear current SftpContext trapped in the AsyncLocals, as its done.
holder.Context = null;
}
// Use an object indirection to hold the SftpContext in the AsyncLocal,
// so it can be cleared in all ExecutionContexts when its cleared.
_sftpContextCurrent.Value = new ContextHolder { Context = value };
}
}
public void SetRemoteContext(byte[] contextBytes) {
Context = StructBytes.FromBytes<SftpContext>(contextBytes);
}
private sealed class ContextHolder {
public SftpContext? Context;
}
}