context.cpp 11.2 KB
Newer Older
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
// Copyright (C) 2019  Nexedi SA and Contributors.
//                     Kirill Smelkov <kirr@nexedi.com>
//
// This program is free software: you can Use, Study, Modify and Redistribute
// it under the terms of the GNU General Public License version 3, or (at your
// option) any later version, as published by the Free Software Foundation.
//
// You can also Link and Combine this program with other software covered by
// the terms of any of the Free Software licenses or any of the Open Source
// Initiative approved licenses and Convey the resulting work. Corresponding
// source of such a combination shall include the source code for all other
// software used.
//
// This program is distributed WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
//
// See COPYING file for full licensing terms.
// See https://www.nexedi.com/licensing for rationale and options.

// Package context mirrors and amends Go package context.
// See context.h for package overview.

#include "golang/context.h"
#include "golang/cxx.h"
#include "golang/errors.h"
#include "golang/sync.h"
#include "golang/time.h"

#include <math.h>
#include <vector>
using std::pair;
using std::make_pair;
using std::vector;


// golang::context::
namespace golang {
namespace context {

using cxx::set;

static bool _ready(chan<structZ> ch);


// _Background implements root context that is never canceled.
struct _Background final : _Context, object {
    void incref() {
        object::incref();
    }
    void decref() {
        if (__decref())
            delete this;
    }

    double          deadline()              { return INFINITY;  }
    chan<structZ>   done()                  { return NULL;      }
    error           err()                   { return NULL;      }
    interface       value(const void *key)  { return NULL;      }
};

static Context _background = adoptref(static_cast<_Context *>(new _Background()));

Context background() {
    return _background;
}


68 69
const global<error> canceled          = errors::New("context canceled");
const global<error> deadlineExceeded  = errors::New("deadline exceeded");
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 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307


// _BaseCtx is the common base for Contexts implemented in this package.
struct _BaseCtx : _Context, object {
    // parents of this context - either _BaseCtx* or generic Context.
    // does not change after setup.
    vector<Context>  _parentv;

    sync::Mutex             _mu;
    set<refptr<_BaseCtx>>   _children; // children of this context - we propagate cancel there
    error                   _err;
    chan<structZ>           _done;     // chan | nil (nil: => see parent)


    void incref() {
        object::incref();
    }
    void decref() {
        if (__decref())
            delete this;
    }
    virtual ~_BaseCtx() {}

    _BaseCtx(chan<structZ> done, const vector<Context>& parentv) {
        _BaseCtx& ctx = *this;

        ctx._parentv    = parentv;

        // chan: if context can be canceled on its own
        // nil:  if context can not be canceled on its own
        ctx._done       = done;
        if (done == NULL) {
            if (parentv.size() != 1)
                panic("BUG: _BaseCtx: done==nil, but len(parentv) != 1");
        }

        ctx._propagateCancel();
    }

    chan<structZ> done() {
        _BaseCtx& ctx = *this;

        if (ctx._done != NULL)
            return ctx._done;
        return ctx._parentv[0]->done();
    }

    error err() {
        _BaseCtx& ctx = *this;

        ctx._mu.lock();
        defer([&]() {
            ctx._mu.unlock();
        });

        return ctx._err;
    }

    interface value(const void *key) {
        _BaseCtx& ctx = *this;

        for (auto parent : ctx._parentv) {
            interface v = parent->value(key);
            if (v != NULL)
                return v;
        }
        return NULL;
    }

    double deadline() {
        _BaseCtx& ctx = *this;

        double d = INFINITY;
        for (auto parent : ctx._parentv) {
            double pd = parent->deadline();
            if (pd < d)
                d = pd;
        }
        return d;
    }


    // _cancel cancels ctx and its children.
    void _cancel(error err) {
        _BaseCtx& ctx = *this;
        return ctx._cancelFrom(NULL, err);
    }

    // _cancelFrom cancels ctx and its children.
    // if cancelFrom != nil it indicates which ctx parent cancellation was the cause for ctx cancel.
    virtual void _cancelFrom(Context cancelFrom, error err) {
        _BaseCtx& ctx = *this;

        set<refptr<_BaseCtx>> children;
        ctx._mu.lock();
            if (ctx._err != NULL) {
                ctx._mu.unlock();
                return; // already canceled
            }

            ctx._err = err;
            ctx._children.swap(children);
        ctx._mu.unlock();

        if (ctx._done != NULL)
            ctx._done.close();

        // no longer need to propagate cancel from parent after we are canceled
        refptr<_BaseCtx> bctx = newref(&ctx);
        for (auto parent : ctx._parentv) {
            if (parent == cancelFrom)
                continue;
            _BaseCtx *_parent = dynamic_cast<_BaseCtx *>(parent._ptr());
            if (_parent != NULL) {
                _parent->_mu.lock();
                    _parent->_children.erase(bctx);
                _parent->_mu.unlock();
            }
        }

        // propagate cancel to children
        Context cctx = newref(static_cast<_Context*>(&ctx));
        for (auto child : children)
            child->_cancelFrom(cctx, err);
    }

    // _propagateCancel establishes setup so that whenever a parent is canceled,
    // ctx and its children are canceled too.
    void _propagateCancel() {
        _BaseCtx& ctx = *this;
        refptr<_BaseCtx> bctx = newref(&ctx);

        vector<Context> pforeignv; // parents with !nil .done() for foreign contexts
        for (auto parent : ctx._parentv) {
            // if parent can never be canceled (e.g. it is background) - we
            // don't need to propagate cancel from it.
            chan<structZ> pdone = parent->done();
            if (pdone == NULL)
                continue;

            // parent is cancellable - glue to propagate cancel from it to us
            _BaseCtx *_parent = dynamic_cast<_BaseCtx *>(parent._ptr());
            if (_parent != NULL) {
                _parent->_mu.lock();
                    if (_parent->_err != NULL)
                        ctx._cancel(_parent->_err);
                    else
                        _parent->_children.insert(bctx);
                _parent->_mu.unlock();
            }
            else {
                if (_ready(pdone))
                    ctx._cancel(parent->err());
                else
                    pforeignv.push_back(parent);
            }
        }

        if (pforeignv.size() == 0)
            return;

        // there are some foreign contexts to propagate cancel from
        go([bctx,pforeignv]() {
            vector<_selcase> sel(1+pforeignv.size());
            sel[0] = bctx->_done.recvs();                   // 0
            for (size_t i=0; i<pforeignv.size(); i++)
                sel[1+i] = pforeignv[i]->done().recvs();    // 1 + ...

            int _ = select(sel);

            // 0. nothing - already canceled
            if (_ > 0)
                bctx->_cancel(pforeignv[_-1]->err());
        });
    }
};

// _CancelCtx is context that can be canceled.
struct _CancelCtx : _BaseCtx {
    _CancelCtx(const vector<Context>& parentv)
            : _BaseCtx(makechan<structZ>(), parentv) {}
};

// _ValueCtx is context that carries key -> value.
struct _ValueCtx : _BaseCtx {
    // (key, value) specific to this context.
    // the rest of the keys are inherited from parents.
    // does not change after setup.
    const void *_key;
    interface   _value;

    _ValueCtx(const void *key, interface value, Context parent)
            : _BaseCtx(NULL, {parent}) {
        _ValueCtx& ctx = *this;

        ctx._key   = key;
        ctx._value = value;
    }

    interface value(const void *key) {
        _ValueCtx& ctx = *this;

        if (ctx._key == key)
            return ctx._value;
        return _BaseCtx::value(key);
    }
};

// _TimeoutCtx is context that is canceled on timeout.
struct _TimeoutCtx : _CancelCtx {
    double       _deadline;
    time::Timer  _timer;

    _TimeoutCtx(double timeout, double deadline, Context parent)
            : _CancelCtx({parent}) {
        _TimeoutCtx& ctx = *this;

        if (timeout <= 0)
            panic("BUG: _TimeoutCtx: timeout <= 0");
        ctx._deadline = deadline;
        refptr<_TimeoutCtx> ctxref = newref(&ctx); // pass ctx reference to timer
        ctx._timer    = time::after_func(timeout, [ctxref]() { ctxref->_cancel(deadlineExceeded); });
    }

    double deadline() {
        _TimeoutCtx& ctx = *this;
        return ctx._deadline;
    }

    // cancel -> stop timer
    void _cancelFrom(Context cancelFrom, error err) {
        _TimeoutCtx& ctx = *this;
        _CancelCtx::_cancelFrom(cancelFrom, err);
        ctx._timer->stop();
    }
};


308
pair<Context, func<void()>>
309 310 311 312 313 314 315 316 317 318 319
with_cancel(Context parent) {
    refptr<_CancelCtx> cctx = adoptref(new _CancelCtx({parent}));
    Context            ctx  = newref  (static_cast<_Context*>(cctx._ptr()));
    return make_pair(ctx, [cctx]() { cctx->_cancel(canceled); });
}

Context
with_value(Context parent, const void *key, interface value) {
    return adoptref(static_cast<_Context*>(new _ValueCtx(key, value, parent)));
}

320
pair<Context, func<void()>>
321 322 323 324 325 326 327 328 329
with_deadline(Context parent, double deadline) {
    // parent's deadline is before deadline -> just use parent
    double pdead = parent->deadline();
    if (pdead <= deadline)
        return with_cancel(parent);

    // timeout <= 0   -> already canceled
    double timeout = deadline - time::now();
    if (timeout <= 0) {
330 331
        Context       ctx;
        func<void()>  cancel;
332 333 334 335 336 337 338 339 340 341
        tie(ctx, cancel) = with_cancel(parent);
        cancel();
        return make_pair(ctx, cancel);
    }

    refptr<_TimeoutCtx> tctx = adoptref(new _TimeoutCtx(timeout, deadline, parent));
    Context             ctx  = newref  (static_cast<_Context*>(tctx._ptr()));
    return make_pair(ctx, [tctx]() { tctx->_cancel(canceled); });
}

342
pair<Context, func<void()>>
343 344 345 346
with_timeout(Context parent, double timeout) {
    return with_deadline(parent, time::now() + timeout);
}

347
pair<Context, func<void()>>
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
merge(Context parent1, Context parent2) {
    refptr<_CancelCtx> cctx = adoptref(new _CancelCtx({parent1, parent2}));
    Context            ctx  = newref  (static_cast<_Context*>(cctx._ptr()));
    return make_pair(ctx, [cctx]() { cctx->_cancel(canceled); });
}

// _ready returns whether channel ch is ready.
static bool _ready(chan<structZ> ch) {
    int _ = select({
            ch.recvs(), // 0
            _default,   // 1
    });
    return (_ == 0);
}

// _tctxchildren returns context's children, assuming context is instance of _BaseCtx.
set<Context> _tctxchildren(Context ctx) {
    _BaseCtx *_bctx = dynamic_cast<_BaseCtx*>(ctx._ptr());
    if (_bctx == NULL)
        panic("context is not instance of golang.context._BaseCtx");

    set<Context> children;
    _bctx->_mu.lock();
    defer([&]() {
        _bctx->_mu.unlock();
    });

    for (auto bchild : _bctx->_children) {
        Context cchild = newref(static_cast<_Context*>(bchild._ptr()));
        children.insert(cchild);
    }

    return children;
}

}}  // golang::context::